Java iterative solution without a fake head

  • 0

    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 to point backwards making sure that we change the and 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 && != null) {
                if (curr == head) head =;
                else =;
                ListNode tmp =;
       = curr;
       = 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.