Swap Nodes in Pairs

Leetcode 24.

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() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//head = [1,2,3,4]
ListNode newOne = new ListNode(-1);
ListNode pre = newOne;
//newOne = [-1,1,2,3,4]
newOne.next = head;
while(pre.next != null && pre.next.next != null){
ListNode l1 = pre.next;
ListNode l2 = pre.next.next;
ListNode next = l2.next;
l1.next = next;
l2.next = l1;
pre.next = l2;
pre = l1;
}

return newOne.next;
}
}