Skip to content

Instantly share code, notes, and snippets.

@paulocuambe
Created October 10, 2023 19:21
Show Gist options
  • Save paulocuambe/5bbff881e4ca6a7ad4d910a81560af8d to your computer and use it in GitHub Desktop.
Save paulocuambe/5bbff881e4ca6a7ad4d910a81560af8d to your computer and use it in GitHub Desktop.
Basic SinglyLinkedList using structs
const std = @import("std");
const stdout = std.io.getStdOut().writer();
const Node = struct {
value: i8,
next: ?*Node = null,
pub fn addAfter(self: *Node, node: *Node) void {
node.next = self;
}
};
const LinkedList = struct {
first: ?*Node,
pub fn prepend(self: *LinkedList, node: *Node) void {
node.next = self.first;
self.first = node;
}
};
pub fn main() !void {
var l1 = Node{ .value = 23 };
try stdout.print("{}\n", .{l1});
var l2 = Node{ .value = 18 };
l1.addAfter(&l2);
try stdout.print("{}\n", .{l2});
var l3 = Node{ .value = -2 };
l2.addAfter(&l3);
var list = LinkedList{ .first = &l3 };
try stdout.print("{}\n", .{list});
var l4 = Node{ .value = 10 };
list.prepend(&l4);
try stdout.print("{}\n", .{list});
}
@paulocuambe
Copy link
Author

Output looks like this if you don't want to run to see the output.

singly_linked_list.Node{ .value = 23, .next = null }
singly_linked_list.Node{ .value = 18, .next = linked.Node{ .value = 23, .next = null } }
singly_linked_list.LinkedList{ .first = linked.Node{ .value = -2, .next = linked.Node{ .value = 18, .next = linked.Node{ ... } } } }
singly_linked_list.LinkedList{ .first = linked.Node{ .value = 10, .next = linked.Node{ .value = -2, .next = linked.Node{ ... } } } }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment