Skip to content

Instantly share code, notes, and snippets.

@jifalops
Last active November 27, 2018 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jifalops/c35bc3a1f17857b18341794cac5be4d9 to your computer and use it in GitHub Desktop.
Save jifalops/c35bc3a1f17857b18341794cac5be4d9 to your computer and use it in GitHub Desktop.
Reversing a linked list
class Node<T> {
Node(this.value, [this.next]);
T value;
Node next;
@override String toString() => '$value $next';
}
Node reverse(Node n) {
Node curr = n.next;
n.next = null; // `n` is the new tail.
while(curr != null) {
Node tmp = curr.next; // Start swap.
curr.next = n; // next => previous
n = curr; // Update loop's previous node.
curr = tmp; // Update loop's current node.
}
return n;
}
// Example
void main() {
final list = Node(1, Node(2, Node(3, Node(4, Node(5)))));
print(list); // 1 2 3 4 5 null
print(reverse(list)); // 5 4 3 2 1 null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment