Java iterative approach using 3 pointers


  • 0
    K
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head==null || head.next == null) return head;		        
            ListNode curr = head;
            ListNode next = curr.next;
            ListNode temp = next.next;
            head = next;
            while(temp != null && temp.next!=null) {
                next.next = curr;
                curr.next = temp.next;
                next = temp.next;
                curr = temp;
                temp = next.next;
            }
            next.next = curr;
            curr.next = temp;
            return head;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.