in reply to Re: Reversing a singly linked list
in thread Reversing a singly linked list

Thanks for the response. And this was very helpful
But one question which I have from your code is that , aren't you creating a new list itself ?
So the original list that was created beginning from the head and all the way down , that still continues to remain unaffected
So after following your approach by creating new tail nodes each time , I agree that we will get a reversed linked list , but the original linked list will continue to be unaffected
How can your approach be modified so that there will exist only one direction of linked list at any time , either forward or backwards ?

Replies are listed 'Best First'.
Re^3: Reversing a singly linked list
by choroba (Cardinal) on Feb 20, 2016 at 17:51 UTC
    You are right. You can either assign the new list to the old one:
    $head = $curr;

    The old nodes will be freed, as there's no reference to the head remaining afterwards. Once the head is gone, the next node can be freed, too, and so on.

    Or, you can use a bit more complicated procedure to invert the list in place:

    $curr = $head; my $tail; while ($curr) { my $next = $curr->{next}; $curr->{next} = $tail; $tail = $curr; $curr = $next; }

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      Awww! Can't believe you missed the opportunity for a list assignment here. :)

      ($curr->{next}, $tail, $curr) = ($tail, $curr, $curr->{next});