Thor
Thor

Reputation: 9

DSA swap node pair leetcode problem error

public ListNode swapPairs(ListNode node) {
    ListNode head = node;
    ListNode cur = node;
    while (head != null && head.next != null) {
        head = reverseList(head, 0);
        head.next = cur.next.next;
        head = head.next;
        cur = head;
    }
    return node;
}

public ListNode reverseList(ListNode node, int counter) {
    if (counter == 1 || node == null || node.next == null) {
        return node;
    } else {
        ListNode newHead = reverseList(node.next, counter++);
        node.next.next = node;
        node.next = null;
        return newHead;
    }
}

So this is a leetcode problem.

for example, if the given linked list is 1->2->3->4->5

then the output should be 2->1->4->3->5.

I saw the correct solution but i want to know why this code is not working. Can anyone please help me to understand this?

Upvotes: -1

Views: 62

Answers (1)

many errors are there , i wont be able to point all of them.

But let me tell you a concept.

let A be a linked list .

now when i do Node c = A.next

this mean c is point A next element right.

Now if i make c=null.

then A.next will also become null.

This is the concept of reference variables.

Meaning if you simply do c=a .then both c and a will point to same linked lint object.

now if you want to make a copy of a to c .you have to make new node and vopy elemnts of c to a .

Now.coming to the question posted here.

you can do two things basically.

either only change the value of linked listelements by swapping. or swap the nodes.

both should ideally work .

the problems with your code are- Here’s a simple breakdown of the errors in your code:

  1. Wrong use of the reverseList function:

You're trying to swap pairs, but you're using a recursive list reversal function. This isn't needed since you just want to swap two nodes, not reverse an entire section.

  1. counter++ issue in reverseList:

counter++ is post-increment, meaning it increases the value after it's used in the recursive call, which prevents the stopping condition from working properly.

  1. Incorrect pointer handling after swapping:

After calling reverseList, you're not properly connecting the rest of the list. The line head.next = cur.next.next; can break the list structure, causing wrong behavior.

  1. Unnecessary complexity:

You're using recursion and a separate function to reverse nodes, but you can directly swap adjacent nodes without extra complexity.

In short, the main errors are incorrect recursion, improper list handling, and using a reversal function when you only need to swap two nodes.

Upvotes: -1

Related Questions