Go言語で片方向連結リストを実装

- (2 min read)

サークルの講義で使うかもしれないので置いとく

わざわざgitにrepo作るのもアレだし

TIP💡

zolaはコードスニペットにlinenosを付け足すと行番号を表示できる。今回はそれを使ってみた。

1// NOTE: 連結リストの実装
2package main
3
4import (
5 "fmt"
6)
7
8type Node struct {
9 data int
10 next *Node
11}
12
13type LinkedList struct {
14 head *Node // 先頭ノード
15}
16
17// 位置を指定して挿入
18func (list *LinkedList) Insert(data int, pos int) error {
19 newNode := &Node{data: data}
20
21 if pos < 0 {
22 return fmt.Errorf("場所がありません: %d", pos)
23 }
24 if pos == 0 {
25 newNode.next = list.head
26 list.head = newNode
27 return nil
28 }
29
30 current := list.head
31
32 for i := 0; i < pos-1; i++ {
33 if current == nil || current.next == nil {
34 return fmt.Errorf("範囲外")
35 }
36 current = current.next
37 }
38
39 newNode.next = current.next
40 current.next = newNode
41
42 return nil
43}
44
45// 位置を指定して削除
46func (list *LinkedList) Delete(pos int) error {
47 if list.head == nil {
48 return fmt.Errorf("リストにデータがありません")
49 }
50
51 if pos < 0 {
52 return fmt.Errorf("場所がありません: %d", pos)
53 }
54
55 if pos == 0 {
56 return fmt.Errorf("場所がありません: %d", pos)
57 }
58
59 current := list.head
60 for i := 0; i < pos-1; i++ {
61 if current == nil || current.next == nil {
62 return fmt.Errorf("範囲外")
63 }
64 current = current.next
65 }
66
67 if current.next == nil {
68 return fmt.Errorf("範囲外")
69 }
70
71 // ポインタの書き換え
72 current.next = current.next.next
73 return nil
74}
75
76func (list *LinkedList) DeleteElegant(pos int) error {
77 if list.head == nil {
78 return fmt.Errorf("リストにデータがありません")
79 }
80
81 if pos < 0 {
82 return fmt.Errorf("場所がありません: %d", pos)
83 }
84
85 p := &list.head
86
87 for i := 0; i < pos; i++ {
88 if *p == nil {
89 return fmt.Errorf("範囲外")
90 }
91 p = &(*p).next
92 }
93 if *p == nil {
94 return fmt.Errorf("position out of range")
95 }
96
97 *p = (*p).next
98 return nil
99}
100
101// リストの全要素を表示
102func (list *LinkedList) Display() {
103 current := list.head
104
105 for current != nil {
106 fmt.Printf("%d -> ", current.data)
107 current = current.next
108 }
109 fmt.Println("nil")
110}
111func main() {
112 list := LinkedList{}
113 list.Insert(10, 0)
114 list.Insert(11, 0)
115 list.Insert(12, 0)
116 list.Display()
117
118 list.Delete(2)
119 list.Display()
120
121 list.Delete(1)
122 list.Display()
123}
124
125

まとめ

Go言語わかりやすくて、ええですねぇ! 🐭 < チョー ワカリヤスイ