arun
arun

Reputation: 89

Swap Linked list pairwise

public ListNode SwapPairs(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }

        var newHead = head.next;
        ListNode a = head; 
        ListNode b = head.next;
        ListNode prev = null;

        while(a != null && b != null) {
            a.next = b.next;
            b.next = a;

            if(prev != null)    
                prev.next = b;
            if(a.next == null)
                break;
            b = a.next.next;
            prev = a;
            a = a.next;
        }

        return newHead;
    }

This code is from leetcode, this one works but what i didnt understand is the use of the prev variable in this code, we are not assigning any values of prev to a or b, but without that the code dosent work, I am not sure wheather this a dumb question or am i not paying attention to anything important. Thanks

Upvotes: 1

Views: 62

Answers (1)

prev does not need to be assigned to any variable. We are using it to track a and updating the reference's next property. It's used for making sure the previous swap chains up with the current swap correctly.

For example, in the 2nd iteration, we want to make sure 1.next points to 4 instead of 3 like it did in the 1st iteration. This can be done be tracking a reference to the previous element of the current pair prev and updating prev.next by reference.

Original:
1 -> 2 -> 3 -> 4 -> NULL

1st Iteration:
2 -> 1 -> 3 -> 4 -> NULL

2nd Iteration:
2 -> 1 [->] 4 -> 3 -> NULL

Upvotes: 2

Related Questions