05 August 2008
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
1
2
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
相对于上一道题,这道题是要求对链表从m到n的区间进行翻转(从位置1开始计算)。方法还是一样的,可以维护指针来标记遍历到哪里了,到m位置处再开始做翻转处理,然后到n位置结束翻转即可。
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
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;//记录翻转前的结点
for (int i = 0, i < m - 1; i++) {//遍历到翻转前的结点
pre = pre.next;
}
ListNode start = pre.next;//开始翻转的第一个结点
ListNode reversing = start.next;//即将要被翻转的结点
// 1 - 2 - 3 - 4 - 5 ; m = 2; n = 4 ---> pre = 1, start = 2, reversing = 3
// dummy-> 1 -> 2 -> 3 -> 4 -> 5
for (int i = 0; i < n - m; i++) {//翻转的区间
start.next = reversing.next;
reversing.next = pre.next;
pre.next = reversing;
reversing = start.next;
}
// 翻转1: dummy->1 - 3 - 2 - 4 - 5; pre = 1, start = 2, reversing = 4
// 翻转2: dummy->1 - 4 - 3 - 2 - 5; pre = 1, start = 2, reversing = 5 (finish)
return dummy.next;
}
}