LeetCode - Swap Nodes in Pairs

1 minute read

Problem description

description

Given a linked list, swap every two adjacent nodes and return its head.

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

Example:

1
Given 1->2->3->4, you should return the list as 2->1->4->3.

Analysis

Basic idea is to divide the LinkedList into two LinkedList and then merge them.

Here’s the code:

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
public class SwapNodesinPairs {

  public ListNode swapPairs(ListNode head) {
    ListNode l1 = new ListNode(0), l2 = new ListNode(0);
    ListNode dummy = new ListNode(0);

    ListNode p1 = l1, p2 = l2;
    boolean flag = true;
    while (head != null) {
      if (flag) {
        p1.next = head;
        p1 = p1.next;
        head = head.next;
        p1.next = null;
        flag = false;
      } else {
        p2.next = head;
        p2 = p2.next;
        head = head.next;
        p2.next = null;
        flag = true;
      }
    }
    flag = true;
    ListNode p = dummy;
    l1 = l1.next;
    l2 = l2.next;
    while (l1 != null || l2 != null) {
      if (flag && l2 != null) {
        p.next = l2;
        l2 = l2.next;
        flag = false;
      } else {
        p.next = l1;
        l1 = l1.next;
        flag = true;
      }
      p = p.next;
    }

    return dummy.next;
  }
}

There’s another solution, which is to swap two nodes in one pass.

What to improve