Created
May 2, 2022 08:38
-
-
Save DutchGhost/431371e28ef57f546c60a13f02191764 to your computer and use it in GitHub Desktop.
Linked list removal
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
const List = struct { | |
const Node = struct { | |
value: u32, | |
next: ?*Node = null, | |
}; | |
head: ?*Node = null, | |
fn addNode(this: *@This(), node: *Node) void { | |
node.next = this.head; | |
this.head = node; | |
} | |
fn removeNode(this: *@This(), node: *Node) void { | |
var current = &this.head; | |
while(current.*) |cur|: ({current = &cur.next;}) { | |
if(cur.value == node.value) { | |
current.* = cur.next; | |
break; | |
} | |
} | |
} | |
fn printList(this: *@This()) void { | |
@import("std").debug.print("PRINT LIST\n", .{}); | |
var current = &this.head; | |
while(current.*) |cur|: ({current = &cur.next;}) { | |
@import("std").debug.print("Node value = {}\n", .{cur.value}); | |
} | |
} | |
}; | |
pub fn main() void { | |
var l = List {}; | |
var n1 = List.Node { .value = 1, }; | |
var n2 = List.Node { .value = 2, }; | |
var n3 = List.Node { .value = 3, }; | |
l.addNode(&n1); | |
l.printList(); | |
l.addNode(&n2); | |
l.printList(); | |
l.addNode(&n3); | |
l.printList(); | |
l.removeNode(&n1); | |
l.printList(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment