Skip to content

Instantly share code, notes, and snippets.

@frankchang0125
Created September 1, 2018 07:40
Show Gist options
  • Save frankchang0125/ca3d409eddc6ead5153759d65d51154f to your computer and use it in GitHub Desktop.
Save frankchang0125/ca3d409eddc6ead5153759d65d51154f to your computer and use it in GitHub Desktop.
707. Design Linked List
type MyLinkedList struct {
head *Node
}
type Node struct {
next *Node
val int
}
/** Initialize your data structure here. */
func Constructor() MyLinkedList {
return MyLinkedList{
head: nil,
}
}
/** 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 {
node := this.head
for i := 0; i < index; i++ {
if node == nil {
return -1
}
node = node.next
}
if node == nil {
return -1
}
return node.val
}
/** 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) {
this.head = &Node{
next: this.head,
val: val,
}
}
/** Append a node of value val to the last element of the linked list. */
func (this *MyLinkedList) AddAtTail(val int) {
if this.head == nil {
this.head = &Node{
next: nil,
val: val,
}
return
}
node := this.head
for {
if node.next == nil {
node.next = &Node{
next: nil,
val: val,
}
return
}
node = node.next
}
}
/** 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 this.head == nil {
if index == 0 {
this.head = &Node{
next: nil,
val: val,
}
return
}
return
}
node := this.head
var i int
// Iterate to (index - 1) node, if possible
for i = 0; i < index-1; i++ {
if node.next != nil {
node = node.next
} else {
return
}
}
node.next = &Node{
next: node.next,
val: val,
}
return
}
/** Delete the index-th node in the linked list, if the index is valid. */
func (this *MyLinkedList) DeleteAtIndex(index int) {
if this.head == nil {
return
}
node := this.head
var i int
// Iterate to (index - 1) node, if possible
for i = 0; i < index-1; i++ {
if node.next != nil {
node = node.next
} else {
return
}
}
if node.next == nil {
return
}
node.next = node.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);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment