For a given linked list, it has 3 common methods: GetByIndex, AddTo(Head/Tail/ToIndex), Delele. Similar to SQL’s CURD. Let’s see how to design a linked list class. 707. Design Linked List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
type Node struct {
Val int
Next *Node
}

type MyLinkedList struct {
virtualNode *Node
size int
}

func Constructor() MyLinkedList {
return MyLinkedList{&Node{}, 0}
}

func (this *MyLinkedList) Get(index int) int {
if index < 0 || index >= this.size {
return -1
}
p := this.virtualNode
for ; index > 0; index-- {
p = p.Next
}
return p.Next.Val
}

func (this *MyLinkedList) AddAtHead(val int) {
this.virtualNode.Next = &Node{val, this.virtualNode.Next}
this.size++
}

func (this *MyLinkedList) AddAtTail(val int) {
p := this.virtualNode
for ; p.Next != nil; p = p.Next {}
p.Next = &Node{val, nil}
this.size++
}

func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index > this.size {
return
}
if index < 0 {
index = 0
}
p := this.virtualNode
for ; index > 0; index-- {
p = p.Next
}
node := &Node{val, p.Next}
p.Next = node
this.size++
}

func (this *MyLinkedList) DeleteAtIndex(index int) {
if index < 0 || index >= this.size {
return
}
p := this.virtualNode
for ; index > 0; index-- {
p = p.Next
}
p.Next = p.Next.Next
this.size--
}