Home > Software design >  what is wrong with this reverse linklist code?
what is wrong with this reverse linklist code?

Time:03-29

 var reverseList = function(head) {
    function reverse(cur,pre){
        if(!cur) return pre
        next = cur.next
        cur.next = pre
        return reverse(next,head)
    }
    return reverse(head.next,head)
}

I tried a recursion way to write this,

this code output is not correct running, whats wrong with this code?

CodePudding user response:

This is what i think:

If we go by your logic for let's say this case (1->2->3->null), then end result is - first node has address of second node in its 'next' & second node has address of first in its 'next'. So, a loop is formed (1->2 and 2->1). If you want to print such a list, it'll end up in an infinite loop kind of situation in an online platform.

As Thomas Mailund has correctly pointed out, null list case also needs to be covered.

I'd also suggest you to keep your variable names distinct from each other to avoid confusion.

(e.g. you used 'next' as variable name in your inner function which is used already for linked list).

Taking these factors into consideration, here's the rectified working version of your code:

var reverseList = function(head) {

    var r = null;

    function reverse(p, q) {
        
    q.next = r;

    r = q;

    if (p == null) return q;

    return reverse(p.next, p);

    }

    return (!head) ? head : reverse(head.next,head)

}
  • Related