forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
79 lines (72 loc) · 1.48 KB
/
Solution.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
type MyLinkedList struct {
e []int
ne []int
head int
idx int
size int
}
func Constructor() MyLinkedList {
e := make([]int, 1000)
ne := make([]int, 1000)
head, idx, size := -1, 0, 0
return MyLinkedList{e, ne, head, idx, size}
}
func (this *MyLinkedList) Get(index int) int {
if index < 0 || index >= this.size {
return -1
}
i := this.head
for ; index > 0; i, index = this.ne[i], index-1 {
}
return this.e[i]
}
func (this *MyLinkedList) AddAtHead(val int) {
this.e[this.idx] = val
this.ne[this.idx] = this.head
this.head = this.idx
this.idx++
this.size++
}
func (this *MyLinkedList) AddAtTail(val int) {
this.AddAtIndex(this.size, val)
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index > this.size {
return
}
if index <= 0 {
this.AddAtHead(val)
return
}
i := this.head
for ; index > 1; i, index = this.ne[i], index-1 {
}
this.e[this.idx] = val
this.ne[this.idx] = this.ne[i]
this.ne[i] = this.idx
this.idx++
this.size++
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
if index < 0 || index >= this.size {
return
}
this.size--
if index == 0 {
this.head = this.ne[this.head]
return
}
i := this.head
for ; index > 1; i, index = this.ne[i], index-1 {
}
this.ne[i] = this.ne[this.ne[i]]
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Get(index);
* obj.AddAtHead(val);
* obj.AddAtTail(val);
* obj.AddAtIndex(index,val);
* obj.DeleteAtIndex(index);
*/