Answers for "swap nodes in pairs leetcode java"

0

swap nodes in pairs leetcode java

public ListNode swapPairs(ListNode head) {
    if(head == null || head.next == null)   
        return head;
 
    ListNode h = new ListNode(0);
    h.next = head;
    ListNode p = h;
 
    while(p.next != null && p.next.next != null){
        //use t1 to track first node
        ListNode t1 = p;
        p = p.next;
        t1.next = p.next;
 
        //use t2 to track next node of the pair
        ListNode t2 = p.next.next;
        p.next.next = p;
        p.next = t2;
    }
 
    return h.next;
}
Posted by: Guest on May-09-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language