Last active
November 27, 2018 18:56
-
-
Save jifalops/c35bc3a1f17857b18341794cac5be4d9 to your computer and use it in GitHub Desktop.
Reversing a linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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