Java iterative solution without a fake head


  • 0
    S

    Hi guys!

    The idea is to use two pointers to current and to previous node. Previous one is used in all iterations except the first one when we just change the head pointer to return it at the end. On each iteration we make curr.next.next to point backwards making sure that we change the prev.next and curr.next properly.

    Check out the code below!
    Hope it helps!


    public class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode curr = head, prev = null;
            while (curr != null && curr.next != null) {
                if (curr == head) head = curr.next;
                else prev.next = curr.next;
                ListNode tmp = curr.next.next;
                curr.next.next = curr;
                curr.next = tmp;
                prev = curr;
                curr = tmp;
            }
            return head;
        }
    }

Log in to reply
 

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