Fork me on GitHub

Swap Nodes in Pairs

Description

https://leetcode.com/problems/swap-nodes-in-pairs/description/

Solution(Sentinel node tricky)

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode pre = new ListNode(0);
if (head == null || head.next == null) return head;
ListNode first = head;
ListNode second = head.next;
pre.next = first;
head = second;
while (true) {
pre.next = second;
pre = first;
ListNode temp = second.next;
second.next = first;
if (temp == null) {
first.next = null;
return head;
}
first = temp;
second = first.next != null ? first.next : first; #Pay attention to the singular case
}
}
}