๐Ÿ“ฆ jtr109 / go-playground

๐Ÿ“„ lib.go ยท 86 lines
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
82
83
84
85
86// https://leetcode.com/problems/design-linked-list/

package designlinkedlist

type MyLinkedList struct {
	Val  int
	Next *MyLinkedList
}

func Constructor() MyLinkedList {
	return MyLinkedList{
		Val: -1,
	}
}

func (this *MyLinkedList) Get(index int) int {
	current := this
	for i := -1; i < index; i++ {
		if current.Next == nil {
			// out of range
			return -1
		}
		current = current.Next
	}
	return current.Val
}

func (this *MyLinkedList) AddAtHead(val int) {
	node := MyLinkedList{
		Val:  val,
		Next: this.Next,
	}
	this.Next = &node
}

func (this *MyLinkedList) AddAtTail(val int) {
	current := this
	for current.Next != nil {
		current = current.Next
	}
	node := MyLinkedList{
		Val: val,
	}
	current.Next = &node
}

func (this *MyLinkedList) AddAtIndex(index int, val int) {
	current := this
	for i := -1; i < index-1; i++ {
		if current.Next == nil {
			// out of range
			return
		}
		current = current.Next
	}
	current.Next = &MyLinkedList{
		Val:  val,
		Next: current.Next,
	}
}

func (this *MyLinkedList) DeleteAtIndex(index int) {
	current := this
	for i := -1; i < index-1; i++ {
		if current.Next == nil {
			// out of range
			return
		}
		current = current.Next
	}
	if current.Next == nil {
		return
	}
	current.Next = current.Next.Next
}

/**
 * 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);
 */