Swap Nodes In Pairs

Swap Nodes In Pairs

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.l”

Solution1

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

/ **
l1 -> 1 -> 2 -> 3 -> 4
|
v
l2

to

2 -> 1 -> 3 -> 4
| |
v v
l1 l2
*/

public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}

ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode l1 = dummy;
ListNode l2 = head;

while (l2 != null && l2.next != null) {
ListNode nextStart = l2.next.next;
l1.next = l2.next;
l2.next.next = l2;
l2.next = nextStart;
l1 = l2;
l2 = l2.next;
}
return dummy.next;
}

Solution2

[Java] recursive solution beats 100% with explanation

1
2
3
4
5
6
7
8
9
10
11
12
13
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}

ListNode tempNext = head.next.next;
ListNode tempFirst = head.next;
ListNode tempSecond = head;
head = tempFirst;
head.next = tempSecond;
head.next.next = swapPairs(tempNext);
return head;
}