2.png
type node struct {
val int
next *node
prev *node
}
type MyLinkedList struct {
head *node
tail *node
length int
}
/** Initialize your data structure here. */
func Constructor() MyLinkedList {
return MyLinkedList{}
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
func (this *MyLinkedList) Get(index int) int {
if index < 0 || index >= this.length {
return -1
}
for cur := this.head; ; cur = cur.next {
if index == 0 {
return cur.val
}
index --
}
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
func (this *MyLinkedList) AddAtHead(val int) {
temp := &node{
val : val,
next: this.head,
prev: nil,
}
if this.head == nil {
this.tail = temp
}else {
this.head.prev = temp
}
this.head = temp
this.length ++
}
/** Append a node of value val to the last element of the linked list. */
func (this *MyLinkedList) AddAtTail(val int) {
temp := &node{
val : val,
next: nil,
prev: this.tail,
}
if this.tail == nil {
this.head = temp
}else {
this.tail.next = temp
}
this.tail = temp
this.length ++
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index < 0 || index > this.length {
return
}
if index == 0 {
this.AddAtHead(val)
return
}
if index == this.length {
this.AddAtTail(val)
return
}
temp := &node{
val : val,
next: nil,
prev: nil,
}
for cur := this.head; ; cur = cur.next {
if index == 0 {
cur.prev.next = temp
temp.next = cur
temp.prev = cur.prev
cur.prev = temp
break
}
index --
}
this.length ++
}
/** Delete the index-th node in the linked list, if the index is valid. */
func (this *MyLinkedList) DeleteAtIndex(index int) {
if index < 0 || index >= this.length {
return
}
if index == 0 {
this.head = this.head.next
if this.head != nil {
this.head.prev = nil
}else {
this.tail = nil
}
this.length --
return
}
if index == this.length - 1 {
this.tail = this.tail.prev
if this.tail != nil {
this.tail.next = nil
}else {
this.head = nil
}
this.length --
return
}
for cur := this.head; ; cur = cur.next {
if index == 0 {
cur.prev.next = cur.next
cur.next.prev = cur.prev
break
}
index --
}
this.length --
}
/**
* 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);
*/
网友评论