Share the joy
leetcode 92.
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
.
Solution. Should return head if head is null or head only has 1 element.
We use a dummyHead pointing to head. Then we put start to the m – 1 position, put pre to m position, put curr to m + 1 position. Each time, we move curr after start. At the beginning, start points to dummyHead. Process for reversing [2..4] is like below.
If there are only 2 elements, the initial is like this:
public static ListNode reverseBetween(ListNode head, int m, int n) { if (head == null || head.next == null) { return head; } ListNode dummyHead = new ListNode(-1); dummyHead.next = head; ListNode start = dummyHead; for (int i = 1; i < m; i++) { start = start.next; } ListNode pre = start.next, curr = start.next.next; for (int i = 1; i <= n - m; i++) { pre.next = curr.next; curr.next = start.next; start.next = curr; curr = pre.next; } return dummyHead.next; }
Check my code on github.
Pingback: Reverse Nodes in k-Group | allenlipeng47()