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);
*/
Design Linked List
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...