in reply to Reversing a singly linked list

You need to wrap the data from the current element in each step, not the whole element:
$curr = $head; my $tail; while ($curr) { $tail = { next => $tail, data => $curr->{data}, }; $curr = $curr->{next}; } print Dumper $tail;
($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,

Replies are listed 'Best First'.
Re^2: Reversing a singly linked list
by Anonymous Monk on Feb 15, 2016 at 16:20 UTC
    OK Thanks for the response...
    But would you be knowing why the following is running into infinite loop ?
    what am I doing wrong here
    ## Reversing linked list $curr=$head; while (defined ($curr->{next})) { $curr->{next} = { data =>$curr->{data}, next => $curr }; $curr = $curr->{next}; } print Dumper $curr;
      Because you always effectively assign next => $curr , hence it's always defined.

      Try Data::Dumper to check if your data is what you think it should be.

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

Re^2: Reversing a singly linked list
by punitpawar (Sexton) on Feb 20, 2016 at 13:14 UTC
    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 ?
      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});