Search code examples
algorithmdata-structureslinked-listsingly-linked-listdoubly-linked-list

I tried solving reverse linkedlist on my own way. please spot the problem reversing the linkedlist


Hi everyone Can you tell me why this code not working for reversing linkedlist I tried my own way to solve but don't get what am I doing wrong

 def reverselist(self):
    temp=self.start
    cur=None
    prev=None
    nxt=None
    while(temp!=None):
        nxt=temp.next
        cur=temp
        cur.next=prev
        prev=cur
        temp=temp.next

Solution

  • Look at these assignments:

        cur=temp
        cur.next=prev
        prev=cur
        temp=temp.next
    

    The one that really mutates the list, is cur.next=prev. There you make the next pointer point backwards. But then after that change, you do temp=temp.next. So you are taking the modified .next value here.

    If that does not clarify it, then realise that temp == cur (the first assignment), so also cur.next == temp.next. If you assign a new value to cur.next, then temp.next will be that new value.

    The solution is to perform temp=temp.next before you change the next pointer:

        cur=temp
        temp=temp.next
        cur.next=prev
        prev=cur
    

    Or, which I find a bit clearer, but really is the same thing:

        cur=temp
        temp=cur.next
        cur.next=prev
        prev=cur
    

    Here you clearly see the pattern: what you have at the right side of the assignment, becomes the left side in the next assignment. This shows clearly that you first read the current value of a variable or property, and then write a new value to it.

    NB: you never read nxt, so you don't need that variable.

    Assign all at once

    In Python you can make multiple assignments in one go, which saves you a variable (prev) because all expressions at the right side are evaluated before any of the assignments happen:

        temp.next, cur, temp = cur, temp, temp.next