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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
| type MyLinkedList struct { node *Node }
type Node struct { val int next *Node prev *Node }
func Constructor() MyLinkedList { node:=&Node{ val:-1, next:nil, prev:nil, } node.next=node node.prev=node return MyLinkedList{node} }
func (this *MyLinkedList) Get(index int) int { head:=this.node.next for head!=this.node && index>0 { index-- head=head.next } if index != 0 { return -1 } return head.val }
func (this *MyLinkedList) AddAtHead(val int) { node:=this.node newnode:=&Node{ val:val, next:node.next, prev:node, } node.next.prev=newnode node.next=newnode }
func (this *MyLinkedList) AddAtTail(val int) { node:=this.node newnode:=&Node{ val:val, next:node, prev:node.prev, } node.prev.next=newnode node.prev=newnode }
func (this *MyLinkedList) AddAtIndex(index int, val int) { if index<0 { this.AddAtHead(val) }else{ head:=this.node.next for head!=this.node && index>0 { index-- head=head.next } if index>0 { return } newnode:=&Node{ val:val, next:head, prev:head.prev, } head.prev.next=newnode head.prev=newnode
}
// head := this.node.next // //head = MyLinkedList[index] // for head != this.node && index > 0 { // head = head.next // index-- // } // if index > 0 { // return // } // node := &Node{ // val: val, // //node.Next = MyLinkedList[index] // next: head, // //node.Pre = MyLinkedList[index-1] // prev: head.prev, // } // //MyLinkedList[index-1].Next = node // head.prev.next = node // //MyLinkedList[index].Pre = node // head.prev = node // //以上两步不能反 }
func (this *MyLinkedList) DeleteAtIndex(index int) { if this.node.next == this.node { return } head:=this.node.next for head.next!=this.node && index>0 { index-- head=head.next } if index==0{ head.prev.next=head.next head.next.prev=head.prev }
}
/** * 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); */
|