Design linkedlist, can use single or double linkedlist, follow is a simple example.
Main linkedlist design.
/**
* 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);
*/
type MyLinkedList struct {
head *Node
}
type Node struct {
Val int
Next *Node
}
func Constructor() MyLinkedList {
linkedlist := new(MyLinkedList)
return *linkedlist
}
func (this *MyLinkedList) Get(index int) int {
current := this.head
for i := 0; current != nil; i++ {
if i == index {
return current.Val
}
current = current.Next
}
return -1
}
func (this *MyLinkedList) AddAtHead(val int) {
node := new(Node)
node.Val = val
node.Next = this.head
this.head = node
}
func (this *MyLinkedList) AddAtTail(val int) {
current := this.head
if this.head == nil {
this.head = &Node{Val: val}
return
}
for ; current.Next != nil; current = current.Next {
}
current.Next = &Node{Val: val}
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index == 0 {
this.AddAtHead(val)
return
}
node := &Node{Val: val}
current := this.head
for i := 0; current != nil; i++ {
fmt.Println(current.Val)
if i == index-1 {
node.Next = current.Next
current.Next = node
break
}
current = current.Next
}
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
current := this.head
if index == 0 {
this.head = this.head.Next
}
for i := 0; current != nil; i++ {
if i+1 == index {
if current.Next != nil {
current.Next = current.Next.Next
break
} else {
break
}
}
current = current.Next
}
}
Other function
func (this *MyLinkedList) Show() {
fmt.Print("Show: ")
current := this.head
for current != nil {
fmt.Print(current.Val, " ")
current = current.Next
}
fmt.Print("\n")
}
func (this *MyLinkedList) Set(nums []int) {
current := this.head
for i := 0; i < len(nums); i++ {
if current == nil {
current = new(Node)
this.head = current
}
current.Val = nums[i]
if i+1 < len(nums) {
temp := new(Node)
current.Next = temp
current = current.Next
}
}
}