Last active
October 7, 2021 06:57
-
-
Save suragch/7cf399b3989e94153b142ded743a6418 to your computer and use it in GitHub Desktop.
linked list
This file contains 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
void main() { | |
popExample(); | |
removeLastExample(); | |
removeAfterExample(); | |
} | |
void popExample() { | |
var list = LinkedList<int>(); | |
list.push(3); | |
list.push(2); | |
list.push(1); | |
print(list); // 1 -> 2 -> 3 | |
list.pop(); | |
print(list); // 2 -> 3 (if you are successful) | |
} | |
void removeLastExample() { | |
var list = LinkedList<int>(); | |
list.push(3); | |
list.push(2); | |
list.push(1); | |
print(list); // 1 -> 2 -> 3 | |
list.removeLast(); | |
print(list); // 1 -> 2 (if you are successful) | |
} | |
void removeAfterExample() { | |
var list = LinkedList<int>(); | |
list.push(77); | |
list.push(42); | |
list.push(3); | |
list.push(2); | |
list.push(1); | |
print(list); // 1 -> 2 -> 3 -> 42 -> 77 | |
final node = list.nodeAt(index: 2); | |
list.removeAfter(node!); | |
print(list); // 1 -> 2 -> 3 -> 77 (if you are successful) | |
} | |
class Node<T> { | |
Node(this.value); | |
T? value; | |
Node<T>? next; | |
@override | |
String toString() { | |
if (next == null) return '$value'; | |
return '$value -> ${next.toString()}'; | |
} | |
} | |
class LinkedList<E> { | |
Node<E>? head; | |
Node<E>? tail; | |
bool get isEmpty => head == null; | |
void push(E value) { | |
final node = Node(value); | |
if (isEmpty) { | |
head = node; | |
tail = node; | |
return; | |
} | |
node.next = head; | |
head = node; | |
} | |
void append(E value) { | |
if (isEmpty) { | |
push(value); | |
return; | |
} | |
final node = Node(value); | |
tail!.next = node; | |
tail = node; | |
} | |
Node<E>? nodeAt({required int index}) { | |
if (isEmpty) { | |
return null; | |
} | |
var currentNode = head; | |
for (var i = 0; i < index; i++) { | |
if (currentNode!.next == null) { | |
return null; | |
} | |
currentNode = currentNode.next; | |
} | |
return currentNode; | |
} | |
void insertAfter(Node<E>? node, E value) { | |
if (node == null) return; | |
final newNode = Node(value); | |
if (isEmpty) { | |
push(value); | |
} else { | |
if (node.next == null) { | |
append(value); | |
return; | |
} | |
newNode.next = node.next; | |
node.next = newNode; | |
} | |
} | |
E? pop() { | |
// TODO: remove head | |
} | |
E? removeLast() { | |
// TODO: remove tail | |
} | |
E? removeAfter(Node<E> node) { | |
// TODO: remove node.next | |
} | |
@override | |
String toString() { | |
if (isEmpty) return 'Empty list'; | |
return head.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment