LeetCode - Reverse Linked List II

1 minute read

Problem description

description

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

Analysis

Draw some graph may help to understand this problem.

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
41
42
43
44
45
46
47
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        
        dummy.next = head;
        
        ListNode p = dummy;
        
        int i = 1;
        
        ListNode s = dummy;
        ListNode e = dummy;
        
        
        while (p.next != null){
            ListNode next = p.next;
            if (i == m){
                s = p;
                e = p.next; // unused pointer
                p = next;
            }
            else if (i > m && i <= n ){
                ListNode first = s.next;
                p.next = next.next;
                next.next = first;
                s.next = next;
            }
            else {
                p = next;
            }
            
            i++;
        }
        
        return dummy.next;
    }
}

What to improve