Leetcode 92. 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
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
解题思路:
反转整个链表的变种,指定了起点和终点。由于m=1时会变动头节点,所以加入一个dummy头节点
1. 找到原链表中第m-1个节点start:反转后的部分将接回改节点后。
从dummy开始移动m-1步
D->1->2->3->4->5->NULL
|
st
2. 将从p = start->next开始,长度为L = n-m+1的部分链表反转。
__________
| |
| V
D->1->2<-3<-4 5->NULL
| | |
st p h0
3. 最后接回
__________
| |
| V
D->1 2<-3<-4 5->NULL
|________|
Java code:
20160601
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { //iterative //base case if (head == null || head.next == null || m < 1 || m >= n) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode cur = head; //move m-1 to the node before reverse start int count = 1; while (count < m) { pre = cur; cur = cur.next; count++; } ListNode beforeReverse = pre; ListNode startReverse = cur; while (count <= n) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; count++; } beforeReverse.next = pre; startReverse.next = cur; return dummy.next; } }
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leetcode-reverse-linked-list-ii.html