// LinkedList //
import "fmt"
// type ListNode struct {
// Val int
// Next *ListNode
// }
type MyLinkedList struct {
Head *ListNode
}
func Constructor() MyLinkedList {
var mll MyLinkedList
return mll
}
func (this *MyLinkedList) Print() {
fmt.Println("Printing LL start")
th := this.Head
for th != nil {
fmt.Println(th.Val)
th = th.Next
}
fmt.Println("Printing LL done")
}
func (this *MyLinkedList) Len() int {
l := 0
th := this.Head
for th != nil {
th = th.Next
l++
}
return l
}
func (this *MyLinkedList) Get(index int) int {
this.Print()
if index >= this.Len() {
return -1
}
th := this.Head
for range index {
th = th.Next
}
if th != nil {
return th.Val
}
return -1
}
func (this *MyLinkedList) AddAtHead(val int) {
var node ListNode
node.Val = val
node.Next = this.Head
this.Head = &node
}
func (this *MyLinkedList) AddAtTail(val int) {
tail := this.Head
var node ListNode
node.Val = val
if tail == nil {
this.Head = &node
return
}
for tail.Next != nil {
tail = tail.Next
}
tail.Next = &node
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index == this.Len() {
this.AddAtTail(val)
return
}
if index > this.Len() {
return
}
var node ListNode
node.Val = val
if index == 0 {
node.Next = this.Head
this.Head = &node
return
}
th := this.Head
for range index-1 {
th = th.Next
}
node.Next = th.Next
th.Next = &node
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
if index >= this.Len() {
return
}
th := this.Head
if index == 0 {
this.Head = this.Head.Next
return
}
for range index-1 {
th = th.Next
}
if th != nil && th.Next != nil {
th.Next = th.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);
*/
// @leet end