forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.go
81 lines (74 loc) · 1.42 KB
/
Solution2.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
80
81
type MyLinkedList struct {
e []int
ne []int
idx int
head int
cnt int
}
func Constructor() MyLinkedList {
e := make([]int, 1010)
ne := make([]int, 1010)
return MyLinkedList{e, ne, 0, -1, 0}
}
func (this *MyLinkedList) Get(index int) int {
if index < 0 || index >= this.cnt {
return -1
}
i := this.head
for ; index > 0; index-- {
i = this.ne[i]
}
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.cnt++
}
func (this *MyLinkedList) AddAtTail(val int) {
this.AddAtIndex(this.cnt, val)
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index > this.cnt {
return
}
if index <= 0 {
this.AddAtHead(val)
return
}
i := this.head
for ; index > 1; index-- {
i = this.ne[i]
}
this.e[this.idx] = val
this.ne[this.idx] = this.ne[i]
this.ne[i] = this.idx
this.idx++
this.cnt++
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
if index < 0 || index >= this.cnt {
return
}
this.cnt--
if index == 0 {
this.head = this.ne[this.head]
return
}
i := this.head
for ; index > 1; index-- {
i = this.ne[i]
}
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);
*/