swap nodes in pairs leetcode java

Solutions on MaxInterview for swap nodes in pairs leetcode java by the best coders in the world

showing results for - "swap nodes in pairs leetcode java"
Felix
13 Jun 2019
1public ListNode swapPairs(ListNode head) {
2    if(head == null || head.next == null)   
3        return head;
4 
5    ListNode h = new ListNode(0);
6    h.next = head;
7    ListNode p = h;
8 
9    while(p.next != null && p.next.next != null){
10        //use t1 to track first node
11        ListNode t1 = p;
12        p = p.next;
13        t1.next = p.next;
14 
15        //use t2 to track next node of the pair
16        ListNode t2 = p.next.next;
17        p.next.next = p;
18        p.next = t2;
19    }
20 
21    return h.next;
22}