Files
hello-algo/ja/codes/zig/utils/ListNode.zig
T
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

50 lines
1.4 KiB
Zig

// File: ListNode.zig
// Created Time: 2023-01-07
// Author: codingonion ([email protected]), CreatorMetaSky ([email protected])
const std = @import("std");
// 連結リストのノード
pub fn ListNode(comptime T: type) type {
return struct {
const Self = @This();
val: T = 0,
next: ?*Self = null,
// 指定された値で連結リストのノードを初期化する
pub fn init(self: *Self, x: i32) void {
self.val = x;
self.next = null;
}
};
}
// リストをデシリアライズして連結リストにする
pub fn listToLinkedList(comptime T: type, allocator: std.mem.Allocator, list: std.ArrayList(T)) !?*ListNode(T) {
var dum = try allocator.create(ListNode(T));
dum.init(0);
var head = dum;
for (list.items) |val| {
var tmp = try allocator.create(ListNode(T));
tmp.init(val);
head.next = tmp;
head = head.next.?;
}
return dum.next;
}
// 配列をデシリアライズして連結リストにする
pub fn arrToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, arr: []T) !?*ListNode(T) {
var dum = try mem_allocator.create(ListNode(T));
dum.init(0);
var head = dum;
for (arr) |val| {
var tmp = try mem_allocator.create(ListNode(T));
tmp.init(val);
head.next = tmp;
head = head.next.?;
}
return dum.next;
}