Created
October 10, 2023 19:21
-
-
Save paulocuambe/5bbff881e4ca6a7ad4d910a81560af8d to your computer and use it in GitHub Desktop.
Basic SinglyLinkedList using structs
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
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}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output looks like this if you don't want to run to see the output.