Skip to content

Latest commit

 

History

History
84 lines (70 loc) · 1.46 KB

707设计链表.md

File metadata and controls

84 lines (70 loc) · 1.46 KB

虚拟头

type MyLinkedList struct {
    dummyHead *Node
    Count int
}

type Node struct {
    val int
    next *Node
}

func Constructor() MyLinkedList {
    dummyHead := &Node{}
    dummyHead.next = nil
    return MyLinkedList{dummyHead, 0}
}


func (this *MyLinkedList) Get(index int) int {
    if index < 0 || index >= this.Count {
        return -1
    }
    curr := this.dummyHead.next
    for index > 0 {
        curr = curr.next
        index--
    }
    return curr.val
}


func (this *MyLinkedList) AddAtHead(val int)  {
    this.AddAtIndex(0, val)
}


func (this *MyLinkedList) AddAtTail(val int)  {
    this.AddAtIndex(this.Count, val)
}


func (this *MyLinkedList) AddAtIndex(index int, val int)  {
    if index > this.Count {
        return
    }
    if index < 0 {
        index = 0
    }
    prev := this.dummyHead
    for index > 0 {
        prev = prev.next
        index--
    }
    newNode := &Node{val, prev.next}
    prev.next = newNode
    this.Count++
}


func (this *MyLinkedList) DeleteAtIndex(index int)  {
    if index < 0 || index >= this.Count {
        return
    }
    prev := this.dummyHead
    for index > 0 {
        prev = prev.next
        index--
    }
    prev.next = prev.next.next
    this.Count--
}


/**
 * 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);
 */