【leetcode】92. reverse linked list ii

1.题目描述

Reverse a linked list from position m to n. Do it in one-pass.

反转从位置 mn 的链表。请使用一趟扫描完成反转。

Note: 1 ≤ mn ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

2.Solutions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static ListNode (ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;

ListNode cur1 = dummy;
ListNode pre1 = null;
for(int i=0;i<m;i++){
pre1 = cur1;
cur1 = cur1.next;
}

//reverse
ListNode cur2 = cur1;
ListNode pre2 = pre1;
ListNode next;
for(int i=m;i<=n;i++){
next = cur2.next;
cur2.next = pre2;
pre2 = cur2;
cur2 = next;
}

//connect
pre1.next = pre2;
cur1.next = cur2;

return dummy.next;
}

参考:【链表】打卡2:如何优雅着反转单链表

(完)