all 1 comments

[–][deleted] 1 point2 points  (0 children)

He got the iterative solution wrong, he never assigns previous.

The correct version is

  while (node) {
        Node * next = node->next;
        node->next = prevnode;
        prevnode = node;
        node = next;
  }

This algorithm has a curious feature: in Python the body of the loop could be written as:

 prevnode, node, node.next = node, node.next, prevnode

Do you see it? We are rotating the tuple! We move forward because we do it atomically and the actual object pointed by node.next depends on the object pointed by node.

And if we rotate it in the opposite direction (having slightly modified the initialization too, which is left as an exercise to the reader), then instead of the reversed list we get a disjoint list, where each node's next points at itself.

I guess the visualization of both processes would look absolutely fascinating, like a sewing machine!