Creating and Managing a Singly Linked List using Heap Memory Allocation in Zig: A Comprehensive Guide
207 views
"Sure! Below is a simple example of a singly linked list in Zig that uses heap memory allocation to create and manage nodes.
Linked List Example in Zig
const std = @import("std");
const Allocator = std.mem.Allocator;
const Node = struct {
value: i32,
next: ?*Node,
};
// Function to create a new node
fn createNode(allocator: *Allocator, value: i32) !*Node {
const node = try allocator.create(Node);
node.* = Node{
.value = value,
.next = null,
};
return node;
}
// Function to append a node to the end of the list
fn appendNode(allocator: *Allocator, head: ?*Node, value: i32) !?*Node {
const newNode = try createNode(allocator, value);
if (head == null) {
return newNode;
}
var current = head;
while (current.?*.next) |next| {
current = next;
}
current.?.next = newNode;
return head;
}
// Function to print the linked list
fn printList(list: ?*Node) void {
var node = list;
while (node != null) {
std.debug.print("{} -> ", .{node.?.value});
node = node.?.next;
}
std.debug.print("null\n", .{});
}
// Function to free the linked list
fn freeList(allocator: *Allocator, list: ?*Node) void {
var node = list;
while (node) |nextNode| {
const next = nextNode.next;
allocator.destroy(nextNode);
node = next;
}
}
pub fn main() !void {
const allocator = std.heap.page_allocator;
var list: ?*Node = null;
list = try appendNode(allocator, list, 1);
list = try appendNode(allocator, list, 2);
list = try appendNode(allocator, list, 3);
list = try appendNode(allocator, list, 4);
std.debug.print("Linked List: ", .{});
printList(list);
freeList(allocator, list);
return;
}
Explanation:
-
Node Structure:
- Defines a
Nodestruct containing avalue(of typei32) and anextpointer that points to the next node in the list or isnull.
- Defines a
-
createNodeFunction: Effectively Managing Requests With Go's Context Package- Takes an allocator and a value, allocates memory for a new node on the heap, initializes it, and returns the pointer to the new node.
-
appendNodeFunction: Mastering For Range Loop: Iterating Collections in Go- Takes an allocator, the current head of the list, and a value. It creates a new node and appends it to the end of the list. If the list is empty, it sets the new node as the head.
-
printListFunction:- Takes the head of the list and prints the values of all nodes in the list sequentially.
-
freeListFunction:- Takes an allocator and the head of the list. It traverses the list, deallocates each node's memory, and ensures no memory leaks.
-
mainFunction:- Uses the standard heap allocator. Demonstrates creating the linked list, appending values, printing the linked list, and finally freeing the allocated memory.
This should be a simple yet comprehensive example to help you understand how linked lists can be managed using heap allocation in Zig!"