LeetCode - Reorder List

1 minute read

Problem description

description

Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3. Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

Analysis

Basically, we can split the LinkedList into two List and reverse the second one and merge them.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
 * 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 void reorderList(ListNode head) {
        if (head == null){
            return;
        }
        
        int size = 0;
        
        ListNode p = head;
        while(p!=null){
            p = p.next;
            size++;
        }
        
        int len1 = size - size/2;
        
        p = head;
        while(len1 > 1){
            p = p.next;
            len1--;
        }
        
        ListNode second = p.next;
        p.next = null;
        
        second = reverse(second);
        
        p = head;
        while(second != null){
            ListNode next = second.next;
            second.next = p.next;
            p.next = second;
            p = second.next;
            second = next;
        }
    }
    
    ListNode reverse(ListNode node){
        if (node == null){
            return null;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = node;
        
        ListNode p = dummy.next;
        
        while (p.next != null){
            ListNode next = p.next.next;
            p.next.next = dummy.next;
            dummy.next = p.next;
            p.next = next;
        }
        
        return dummy.next;
    }
}

For the reverse part

1
2
3
4
5
6
7
8
9
10
11
// reverse the second part of the list [Problem 206]
// convert 1->2->3->4->5->6 into 1->2->3->4 and 6->5->4
// reverse the second half in-place
ListNode prev = null, curr = slow, tmp;
while (curr != null) {
  tmp = curr.next;

  curr.next = prev;
  prev = curr;
  curr = tmp;
}

What to improve

  • for the reverse part, need to be more familiar with that.

  • to get the half of the list, we can use fast and slow pointer to do that.