design linked list

leetcode地址

type MyLinkedList struct {
    v int
    n *MyLinkedList
}

/** 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 {
    r := -1
    c := this.n
    for i := 0; i < index && c != nil; i++ {
        c = c.n
    }
    if c != nil {
        r = c.v
    }

    return r
}

/** 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.n = &MyLinkedList{
        v: val,
        n: this.n,
    }
}

/** Append a node of value val to the last element of the linked list. */
func (this *MyLinkedList) AddAtTail(val int) {
    c := this
    for c.n != nil {
        c = c.n
    }
    c.n = &MyLinkedList{
        v: val,
    }
}

/** 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) {
    defer func() {
        if err := recover(); err != nil {

        }
    }()
    pre := this
    c := this
    for i := 0; i < index; i++ {
        c = c.n
        pre = c
    }
    pre.n = &MyLinkedList{
        v: val,
        n: c.n,
    }
}

/** Delete the index-th node in the linked list, if the index is valid. */
func (this *MyLinkedList) DeleteAtIndex(index int) {
    defer func() {
        if err := recover(); err != nil {

        }
    }()
    pre, c := this, this.n
    for i := 0; i <= index; i++ {
        if i == index {
            pre.n = c.n
        }
        c, pre = c.n, c
    }
}

你可能感兴趣的:(design linked list)