-
-
Save joetifa2003/3065bdda402337e41e9d63c5e1016bd2 to your computer and use it in GitHub Desktop.
ZigFault
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(); | |
fn LinkedList(comptime valueType: type) type { | |
return struct { | |
head: ?*Node, | |
tail: ?*Node, | |
allocator: std.mem.Allocator, | |
const Self = @This(); | |
const Allocator = Self.allocator; | |
const Node = struct { | |
const NSelf = @This(); | |
value: valueType, | |
next: ?*Node = null, | |
prev: ?*Node = null, | |
fn create(allocator: std.mem.Allocator, value: valueType) !*Node { | |
var node = try allocator.create(Node); | |
node.value = value; | |
return node; | |
} | |
}; | |
fn create(allocator: std.mem.Allocator) !*LinkedList(valueType) { | |
const ll = try allocator.create(LinkedList(valueType)); | |
ll.allocator = allocator; | |
return ll; | |
} | |
fn destroy(self: *Self) !void { | |
self.allocator.destroy(self); | |
} | |
fn countt(self: *Self) usize { | |
var count: usize = 0; | |
var it: ?*Node = self.head; | |
while (it) |n| : (it = n.next) { | |
count += 1; | |
} | |
return count; | |
} | |
fn push_back(self: *Self, value: valueType) !void { | |
if (self.head == null) { | |
const node = try Node.create(self.allocator, value); | |
self.head = node; | |
self.tail = node; | |
return; | |
} | |
} | |
}; | |
} | |
const LinkedListInts = LinkedList(i32); | |
pub fn main() !void { | |
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
const allocator = gpa.allocator(); | |
defer { | |
_ = gpa.deinit(); | |
} | |
var ll = try LinkedListInts.create(allocator); | |
try ll.push_back(8); | |
_ = ll.countt(); | |
try ll.destroy(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment