Skip to content

Instantly share code, notes, and snippets.

@DutchGhost
Created May 2, 2022 08:38
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 DutchGhost/431371e28ef57f546c60a13f02191764 to your computer and use it in GitHub Desktop.
Save DutchGhost/431371e28ef57f546c60a13f02191764 to your computer and use it in GitHub Desktop.
Linked list removal
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