Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Analysis
- Create a dummy node
- 初始化3个nodes
- Pre: 指向mth node的前一个(固定)
- Start:指向mth node(固定)
- Then:指向m+1th node(不固定,指向想要移到前面的node)
- For循环,每次把then指向的node插入到pre和start之间
- start.next = then.next
- pre.next = then;
- then.next = start;
- then = start.next;
- Return dummy.next;
Code
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) {return null;}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for (int i=0; i<m-1; i++){
pre = pre.next;
}
ListNode start = pre.next;
ListNode then = start.next;
// 1 - 2 -3 - 4 - 5 ; m=2; n =4 ---> pre = 1, start = 2, then = 3
// dummy-> 1 -> 2 -> 3 -> 4 -> 5
for (int i=0; i<n-m; i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
//after one round
//1->3->2->4->5; pre=1, start=2, then=4
//after two rounds
//1->4->3->2->5; pre=1, start=2, then=5 (finish)
return dummy.next;
}
}
Reference
Node
reverse的方法需要记忆