mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-22 03:32:42 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
140
en/codes/zig/chapter_stack_and_queue/array_queue.zig
Normal file
140
en/codes/zig/chapter_stack_and_queue/array_queue.zig
Normal file
@@ -0,0 +1,140 @@
|
||||
// File: array_queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Queue implemented with a circular array
|
||||
pub fn ArrayQueue(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
nums: []T = undefined, // Array that stores the queue elements
|
||||
cap: usize = 0, // Queue capacity
|
||||
front: usize = 0, // Index of the front element
|
||||
queSize: usize = 0, // Current number of queue elements
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Allocate and initialize the backing array
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator, cap: usize) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
self.cap = cap;
|
||||
self.nums = try self.mem_allocator.alloc(T, self.cap);
|
||||
@memset(self.nums, @as(T, 0));
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the queue capacity
|
||||
pub fn capacity(self: *Self) usize {
|
||||
return self.cap;
|
||||
}
|
||||
|
||||
// Get the queue size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.queSize;
|
||||
}
|
||||
|
||||
// Check whether the queue is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.queSize == 0;
|
||||
}
|
||||
|
||||
// Enqueue
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
if (self.size() == self.capacity()) {
|
||||
std.debug.print("Queue is full\n", .{});
|
||||
return;
|
||||
}
|
||||
// Calculate the index immediately after the rear element
|
||||
// Use modulo to wrap rear to the beginning when it passes the end of the array
|
||||
var rear = (self.front + self.queSize) % self.capacity();
|
||||
// Append num at the rear of the queue
|
||||
self.nums[rear] = num;
|
||||
self.queSize += 1;
|
||||
}
|
||||
|
||||
// Dequeue
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
// Advance the front index by one, wrapping to the start of the array if necessary
|
||||
self.front = (self.front + 1) % self.capacity();
|
||||
self.queSize -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// Access the front element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Queue is empty");
|
||||
return self.nums[self.front];
|
||||
}
|
||||
|
||||
// Return a copy of the queue elements as an array
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
// Copy only the occupied queue elements
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
var j: usize = self.front;
|
||||
while (i < self.size()) : ({ i += 1; j += 1; }) {
|
||||
res[i] = self.nums[j % self.capacity()];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the queue
|
||||
var capacity: usize = 10;
|
||||
var queue = ArrayQueue(i32){};
|
||||
try queue.init(std.heap.page_allocator, capacity);
|
||||
defer queue.deinit();
|
||||
|
||||
// Enqueue elements
|
||||
try queue.push(1);
|
||||
try queue.push(3);
|
||||
try queue.push(2);
|
||||
try queue.push(5);
|
||||
try queue.push(4);
|
||||
std.debug.print("Queue queue = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Access the front element
|
||||
var peek = queue.peek();
|
||||
std.debug.print("\nFront element peek = {}", .{peek});
|
||||
|
||||
// Dequeue an element
|
||||
var pop = queue.pop();
|
||||
std.debug.print("\nDequeued element pop = {}; after dequeueing, queue = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Get the queue size
|
||||
var size = queue.size();
|
||||
std.debug.print("\nQueue size = {}", .{size});
|
||||
|
||||
// Check whether the queue is empty
|
||||
var is_empty = queue.isEmpty();
|
||||
std.debug.print("\nIs the queue empty? {}", .{is_empty});
|
||||
|
||||
// Test the circular array
|
||||
var i: i32 = 0;
|
||||
while (i < 10) : (i += 1) {
|
||||
try queue.push(i);
|
||||
_ = queue.pop();
|
||||
std.debug.print("\nAfter enqueue/dequeue round {}, queue = ", .{i});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
}
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
97
en/codes/zig/chapter_stack_and_queue/array_stack.zig
Normal file
97
en/codes/zig/chapter_stack_and_queue/array_stack.zig
Normal file
@@ -0,0 +1,97 @@
|
||||
// File: array_stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Stack implemented with an array
|
||||
pub fn ArrayStack(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
stack: ?std.ArrayList(T) = null,
|
||||
|
||||
// Initialize the stack's ArrayList
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) void {
|
||||
if (self.stack == null) {
|
||||
self.stack = std.ArrayList(T).init(allocator);
|
||||
}
|
||||
}
|
||||
|
||||
// Deinitialize and release the memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.stack == null) return;
|
||||
self.stack.?.deinit();
|
||||
}
|
||||
|
||||
// Get the stack size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.stack.?.items.len;
|
||||
}
|
||||
|
||||
// Check whether the stack is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Access the top element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Stack is empty");
|
||||
return self.stack.?.items[self.size() - 1];
|
||||
}
|
||||
|
||||
// Push
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
try self.stack.?.append(num);
|
||||
}
|
||||
|
||||
// Pop
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.stack.?.pop();
|
||||
return num;
|
||||
}
|
||||
|
||||
// Return the backing ArrayList
|
||||
pub fn toList(self: *Self) std.ArrayList(T) {
|
||||
return self.stack.?;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the stack
|
||||
var stack = ArrayStack(i32){};
|
||||
stack.init(std.heap.page_allocator);
|
||||
// Defer releasing the memory
|
||||
defer stack.deinit();
|
||||
|
||||
// Push elements onto the stack
|
||||
try stack.push(1);
|
||||
try stack.push(3);
|
||||
try stack.push(2);
|
||||
try stack.push(5);
|
||||
try stack.push(4);
|
||||
std.debug.print("Stack stack = ", .{});
|
||||
inc.PrintUtil.printList(i32, stack.toList());
|
||||
|
||||
// Access the top element
|
||||
var peek = stack.peek();
|
||||
std.debug.print("\nTop element peek = {}", .{peek});
|
||||
|
||||
// Pop an element from the stack
|
||||
var top = stack.pop();
|
||||
std.debug.print("\nPopped element top = {}; after popping, stack = ", .{top});
|
||||
inc.PrintUtil.printList(i32, stack.toList());
|
||||
|
||||
// Get the stack size
|
||||
var size = stack.size();
|
||||
std.debug.print("\nStack size = {}", .{size});
|
||||
|
||||
// Check whether the stack is empty
|
||||
var is_empty = stack.isEmpty();
|
||||
std.debug.print("\nIs the stack empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
51
en/codes/zig/chapter_stack_and_queue/deque.zig
Normal file
51
en/codes/zig/chapter_stack_and_queue/deque.zig
Normal file
@@ -0,0 +1,51 @@
|
||||
// File: deque.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the deque
|
||||
const L = std.TailQueue(i32);
|
||||
var deque = L{};
|
||||
|
||||
// Enqueue elements
|
||||
var node1 = L.Node{ .data = 2 };
|
||||
var node2 = L.Node{ .data = 5 };
|
||||
var node3 = L.Node{ .data = 4 };
|
||||
var node4 = L.Node{ .data = 3 };
|
||||
var node5 = L.Node{ .data = 1 };
|
||||
deque.append(&node1); // Add to the rear
|
||||
deque.append(&node2);
|
||||
deque.append(&node3);
|
||||
deque.prepend(&node4); // Add to the front
|
||||
deque.prepend(&node5);
|
||||
std.debug.print("Deque deque = ", .{});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
|
||||
// Access an element
|
||||
var peek_first = deque.first.?.data; // Front element
|
||||
std.debug.print("\nFront element peek_first = {}", .{peek_first});
|
||||
var peek_last = deque.last.?.data; // Rear element
|
||||
std.debug.print("\nRear element peek_last = {}", .{peek_last});
|
||||
|
||||
// Dequeue an element
|
||||
var pop_first = deque.popFirst().?.data; // Dequeue the front element
|
||||
std.debug.print("\nRemoved front element pop_first = {}; deque = ", .{pop_first});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
var pop_last = deque.pop().?.data; // Dequeue the rear element
|
||||
std.debug.print("\nRemoved rear element pop_last = {}; deque = ", .{pop_last});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
|
||||
// Get the deque size
|
||||
var size = deque.len;
|
||||
std.debug.print("\nDeque size = {}", .{size});
|
||||
|
||||
// Check whether the deque is empty
|
||||
var is_empty = if (deque.len == 0) true else false;
|
||||
std.debug.print("\nIs the deque empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
209
en/codes/zig/chapter_stack_and_queue/linkedlist_deque.zig
Normal file
209
en/codes/zig/chapter_stack_and_queue/linkedlist_deque.zig
Normal file
@@ -0,0 +1,209 @@
|
||||
// File: linkedlist_deque.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Doubly linked list node
|
||||
pub fn ListNode(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
val: T = undefined, // Node value
|
||||
next: ?*Self = null, // Pointer to the next node
|
||||
prev: ?*Self = null, // Pointer to the previous node
|
||||
|
||||
// Initialize a list node with the specified value
|
||||
pub fn init(self: *Self, x: i32) void {
|
||||
self.val = x;
|
||||
self.next = null;
|
||||
self.prev = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Deque implemented with a doubly linked list
|
||||
pub fn LinkedListDeque(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
front: ?*ListNode(T) = null, // Head node front
|
||||
rear: ?*ListNode(T) = null, // Tail node rear
|
||||
que_size: usize = 0, // Deque size
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize an empty deque and its arena allocator
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
self.front = null;
|
||||
self.rear = null;
|
||||
self.que_size = 0;
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the deque size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.que_size;
|
||||
}
|
||||
|
||||
// Check whether the deque is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Enqueue operation
|
||||
pub fn push(self: *Self, num: T, is_front: bool) !void {
|
||||
var node = try self.mem_allocator.create(ListNode(T));
|
||||
node.init(num);
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
if (self.isEmpty()) {
|
||||
self.front = node;
|
||||
self.rear = node;
|
||||
// Enqueue at the front
|
||||
} else if (is_front) {
|
||||
// Add node to the head of the linked list
|
||||
self.front.?.prev = node;
|
||||
node.next = self.front;
|
||||
self.front = node; // Update the head node
|
||||
// Enqueue at the rear
|
||||
} else {
|
||||
// Add node to the tail of the linked list
|
||||
self.rear.?.next = node;
|
||||
node.prev = self.rear;
|
||||
self.rear = node; // Update the tail node
|
||||
}
|
||||
self.que_size += 1; // Update the queue size
|
||||
}
|
||||
|
||||
// Enqueue at the front
|
||||
pub fn pushFirst(self: *Self, num: T) !void {
|
||||
try self.push(num, true);
|
||||
}
|
||||
|
||||
// Enqueue at the rear
|
||||
pub fn pushLast(self: *Self, num: T) !void {
|
||||
try self.push(num, false);
|
||||
}
|
||||
|
||||
// Dequeue operation
|
||||
pub fn pop(self: *Self, is_front: bool) T {
|
||||
if (self.isEmpty()) @panic("Deque is empty");
|
||||
var val: T = undefined;
|
||||
// When the queue size is 1, the head and tail point to the same node
|
||||
if (self.que_size == 1) {
|
||||
val = self.front.?.val;
|
||||
self.front = null;
|
||||
self.rear = null;
|
||||
}
|
||||
// Dequeue from the front
|
||||
else if (is_front) {
|
||||
val = self.front.?.val; // Save the head node value
|
||||
// Remove the head node
|
||||
var fNext = self.front.?.next;
|
||||
fNext.?.prev = null;
|
||||
self.front.?.next = null;
|
||||
self.front = fNext; // Update the head node
|
||||
// Dequeue from the rear
|
||||
} else {
|
||||
val = self.rear.?.val; // Save the tail node value
|
||||
// Remove the tail node
|
||||
var rPrev = self.rear.?.prev;
|
||||
rPrev.?.next = null;
|
||||
self.rear.?.prev = null;
|
||||
self.rear = rPrev; // Update the tail node
|
||||
}
|
||||
self.que_size -= 1; // Update the queue size
|
||||
return val;
|
||||
}
|
||||
|
||||
// Dequeue from the front
|
||||
pub fn popFirst(self: *Self) T {
|
||||
return self.pop(true);
|
||||
}
|
||||
|
||||
// Dequeue from the rear
|
||||
pub fn popLast(self: *Self) T {
|
||||
return self.pop(false);
|
||||
}
|
||||
|
||||
// Access the front element
|
||||
pub fn peekFirst(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Deque is empty");
|
||||
return self.front.?.val;
|
||||
}
|
||||
|
||||
// Access the rear element
|
||||
pub fn peekLast(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Deque is empty");
|
||||
return self.rear.?.val;
|
||||
}
|
||||
|
||||
// Return an array for printing
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.front;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[i] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the deque
|
||||
var deque = LinkedListDeque(i32){};
|
||||
try deque.init(std.heap.page_allocator);
|
||||
defer deque.deinit();
|
||||
try deque.pushLast(3);
|
||||
try deque.pushLast(2);
|
||||
try deque.pushLast(5);
|
||||
std.debug.print("Deque deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// Access an element
|
||||
var peek_first = deque.peekFirst();
|
||||
std.debug.print("\nFront element peek_first = {}", .{peek_first});
|
||||
var peek_last = deque.peekLast();
|
||||
std.debug.print("\nRear element peek_last = {}", .{peek_last});
|
||||
|
||||
// Enqueue elements
|
||||
try deque.pushLast(4);
|
||||
std.debug.print("\nAfter enqueuing element 4 at the rear, deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
try deque.pushFirst(1);
|
||||
std.debug.print("\nAfter enqueuing element 1 at the front, deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// Dequeue an element
|
||||
var pop_last = deque.popLast();
|
||||
std.debug.print("\nElement removed from the rear = {}; after removal, deque = ", .{pop_last});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
var pop_first = deque.popFirst();
|
||||
std.debug.print("\nElement removed from the front = {}; after removal, deque = ", .{pop_first});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// Get the deque size
|
||||
var size = deque.size();
|
||||
std.debug.print("\nDeque size = {}", .{size});
|
||||
|
||||
// Check whether the deque is empty
|
||||
var is_empty = deque.isEmpty();
|
||||
std.debug.print("\nIs the deque empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
127
en/codes/zig/chapter_stack_and_queue/linkedlist_queue.zig
Normal file
127
en/codes/zig/chapter_stack_and_queue/linkedlist_queue.zig
Normal file
@@ -0,0 +1,127 @@
|
||||
// File: linkedlist_queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Queue implemented with a linked list
|
||||
pub fn LinkedListQueue(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
front: ?*inc.ListNode(T) = null, // Head node front
|
||||
rear: ?*inc.ListNode(T) = null, // Tail node rear
|
||||
que_size: usize = 0, // Queue size
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize an empty queue and its arena allocator
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
self.front = null;
|
||||
self.rear = null;
|
||||
self.que_size = 0;
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the queue size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.que_size;
|
||||
}
|
||||
|
||||
// Check whether the queue is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Access the front element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.size() == 0) @panic("Queue is empty");
|
||||
return self.front.?.val;
|
||||
}
|
||||
|
||||
// Enqueue
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
// Add num after the tail node
|
||||
var node = try self.mem_allocator.create(inc.ListNode(T));
|
||||
node.init(num);
|
||||
// If the queue is empty, make both the head and tail point to this node
|
||||
if (self.front == null) {
|
||||
self.front = node;
|
||||
self.rear = node;
|
||||
// If the queue is not empty, add this node after the tail node
|
||||
} else {
|
||||
self.rear.?.next = node;
|
||||
self.rear = node;
|
||||
}
|
||||
self.que_size += 1;
|
||||
}
|
||||
|
||||
// Dequeue
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
// Remove the head node
|
||||
self.front = self.front.?.next;
|
||||
self.que_size -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// Copy the linked-list elements into an array
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.front;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[i] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the queue
|
||||
var queue = LinkedListQueue(i32){};
|
||||
try queue.init(std.heap.page_allocator);
|
||||
defer queue.deinit();
|
||||
|
||||
// Enqueue elements
|
||||
try queue.push(1);
|
||||
try queue.push(3);
|
||||
try queue.push(2);
|
||||
try queue.push(5);
|
||||
try queue.push(4);
|
||||
std.debug.print("Queue queue = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Access the front element
|
||||
var peek = queue.peek();
|
||||
std.debug.print("\nFront element peek = {}", .{peek});
|
||||
|
||||
// Dequeue an element
|
||||
var pop = queue.pop();
|
||||
std.debug.print("\nDequeued element pop = {}; after dequeueing, queue = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Get the queue size
|
||||
var size = queue.size();
|
||||
std.debug.print("\nQueue size = {}", .{size});
|
||||
|
||||
// Check whether the queue is empty
|
||||
var is_empty = queue.isEmpty();
|
||||
std.debug.print("\nIs the queue empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
118
en/codes/zig/chapter_stack_and_queue/linkedlist_stack.zig
Normal file
118
en/codes/zig/chapter_stack_and_queue/linkedlist_stack.zig
Normal file
@@ -0,0 +1,118 @@
|
||||
// File: linkedlist_stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Stack implemented with a linked list
|
||||
pub fn LinkedListStack(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
stack_top: ?*inc.ListNode(T) = null, // Use the head node as the stack top
|
||||
stk_size: usize = 0, // Stack size
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize an empty stack and its arena allocator
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
self.stack_top = null;
|
||||
self.stk_size = 0;
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the stack size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.stk_size;
|
||||
}
|
||||
|
||||
// Check whether the stack is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Access the top element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.size() == 0) @panic("Stack is empty");
|
||||
return self.stack_top.?.val;
|
||||
}
|
||||
|
||||
// Push
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
var node = try self.mem_allocator.create(inc.ListNode(T));
|
||||
node.init(num);
|
||||
node.next = self.stack_top;
|
||||
self.stack_top = node;
|
||||
self.stk_size += 1;
|
||||
}
|
||||
|
||||
// Pop
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
self.stack_top = self.stack_top.?.next;
|
||||
self.stk_size -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// Copy the stack elements into an array
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.stack_top;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[res.len - i - 1] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the stack
|
||||
var stack = LinkedListStack(i32){};
|
||||
try stack.init(std.heap.page_allocator);
|
||||
// Defer releasing the memory
|
||||
defer stack.deinit();
|
||||
|
||||
// Push elements onto the stack
|
||||
try stack.push(1);
|
||||
try stack.push(3);
|
||||
try stack.push(2);
|
||||
try stack.push(5);
|
||||
try stack.push(4);
|
||||
std.debug.print("Stack stack = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try stack.toArray());
|
||||
|
||||
// Access the top element
|
||||
var peek = stack.peek();
|
||||
std.debug.print("\nTop element peek = {}", .{peek});
|
||||
|
||||
// Pop an element from the stack
|
||||
var pop = stack.pop();
|
||||
std.debug.print("\nPopped element pop = {}; after popping, stack = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try stack.toArray());
|
||||
|
||||
// Get the stack size
|
||||
var size = stack.size();
|
||||
std.debug.print("\nStack size = {}", .{size});
|
||||
|
||||
// Check whether the stack is empty
|
||||
var is_empty = stack.isEmpty();
|
||||
std.debug.print("\nIs the stack empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
46
en/codes/zig/chapter_stack_and_queue/queue.zig
Normal file
46
en/codes/zig/chapter_stack_and_queue/queue.zig
Normal file
@@ -0,0 +1,46 @@
|
||||
// File: queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the queue
|
||||
const L = std.TailQueue(i32);
|
||||
var queue = L{};
|
||||
|
||||
// Enqueue elements
|
||||
var node1 = L.Node{ .data = 1 };
|
||||
var node2 = L.Node{ .data = 3 };
|
||||
var node3 = L.Node{ .data = 2 };
|
||||
var node4 = L.Node{ .data = 5 };
|
||||
var node5 = L.Node{ .data = 4 };
|
||||
queue.append(&node1);
|
||||
queue.append(&node2);
|
||||
queue.append(&node3);
|
||||
queue.append(&node4);
|
||||
queue.append(&node5);
|
||||
std.debug.print("Queue queue = ", .{});
|
||||
inc.PrintUtil.printQueue(i32, queue);
|
||||
|
||||
// Access the front element
|
||||
var peek = queue.first.?.data;
|
||||
std.debug.print("\nFront element peek = {}", .{peek});
|
||||
|
||||
// Dequeue an element
|
||||
var pop = queue.popFirst().?.data;
|
||||
std.debug.print("\nDequeued element pop = {}; after dequeueing, queue = ", .{pop});
|
||||
inc.PrintUtil.printQueue(i32, queue);
|
||||
|
||||
// Get the queue size
|
||||
var size = queue.len;
|
||||
std.debug.print("\nQueue size = {}", .{size});
|
||||
|
||||
// Check whether the queue is empty
|
||||
var is_empty = if (queue.len == 0) true else false;
|
||||
std.debug.print("\nIs the queue empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
43
en/codes/zig/chapter_stack_and_queue/stack.zig
Normal file
43
en/codes/zig/chapter_stack_and_queue/stack.zig
Normal file
@@ -0,0 +1,43 @@
|
||||
// File: stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the stack
|
||||
// In Zig, ArrayList can be used as a stack
|
||||
var stack = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
// Defer releasing the memory
|
||||
defer stack.deinit();
|
||||
|
||||
// Push elements onto the stack
|
||||
try stack.append(1);
|
||||
try stack.append(3);
|
||||
try stack.append(2);
|
||||
try stack.append(5);
|
||||
try stack.append(4);
|
||||
std.debug.print("Stack stack = ", .{});
|
||||
inc.PrintUtil.printList(i32, stack);
|
||||
|
||||
// Access the top element
|
||||
var peek = stack.items[stack.items.len - 1];
|
||||
std.debug.print("\nTop element peek = {}", .{peek});
|
||||
|
||||
// Pop an element from the stack
|
||||
var pop = stack.pop();
|
||||
std.debug.print("\nPopped element pop = {}; after popping, stack = ", .{pop});
|
||||
inc.PrintUtil.printList(i32, stack);
|
||||
|
||||
// Get the stack size
|
||||
var size = stack.items.len;
|
||||
std.debug.print("\nStack size = {}", .{size});
|
||||
|
||||
// Check whether the stack is empty
|
||||
var is_empty = if (stack.items.len == 0) true else false;
|
||||
std.debug.print("\nIs the stack empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
Reference in New Issue
Block a user