Go: SingleLinkedList 单向链表

package main

import (
    "fmt"
)

type node struct {
    id   int
    name string
    next *node // Node会造成循环引用
}

type SingleLinkedList struct {
    head   *node // head!=nil 要进行与nil比较, struct zero value不能为nil
    length int
}

// Append 尾部追加
func (list *SingleLinkedList) Append(id int, name string) {
    head := list.head
    if head == nil { // 没有任何元素
        list.head = &node{ // 对原list操作
            id:   id,
            name: name,
        }
        list.length++
        return
    }
    for {
        if head.next == nil { // 最后一个node
            break
        }
        head = head.next
    }
    fmt.Printf("head.next:%v\n", head)
    head.next = &node{
        id:   id,
        name: name,
    }
    list.length++
}

// Insert 根据id升序插入
func (list *SingleLinkedList) Insert(id int, name string) {
    head := list.head
    if head == nil { // SingleLinkedList为空
        list.Append(id, name)
        return
    }

    var prev *node
    for {
        if head.id > id { // 插入到head前
            item := &node{
                id:   id,
                name: name,
            }
            if head == list.head { // 插入到第一个
                list.head = item
                item.next = head
                list.length++
                return
            }
            prev.next = item
            item.next = head
            list.length++
            return
        } else if id == head.id {
            fmt.Printf("id %d exists\n", id)
            return
        }

        prev = head
        head = head.next
        if head.next == nil {
            list.Append(id, name)
            return
        }
    }
}

// Delete 根据id删除node
func (list *SingleLinkedList) Delete(id int) {
    head := list.head
    var prev *node
    if head == nil {
        fmt.Println("list is empty")
    }
    for {
        if id == head.id {
            if head == list.head {
                list.head = list.head.next
                head.next = nil
                list.length--
                return
            }
            prev.next = head.next
            head.next = nil
            list.length--
            return
        }
        prev = head
        head = head.next
        if head == nil {
            fmt.Printf("id %d not exist\n", id)
        }
    }
}

// Show 显示单向链表
func (list *SingleLinkedList) Show() {
    head := list.head
    if head == nil {
        fmt.Println("empty SingleLinkedList")
        return
    }
    fmt.Printf("length: %d\n", list.length)
    for {
        fmt.Printf("%d %s\n", head.id, head.name)
        head = head.next
        if head == nil {
            break
        }
    }
}
func main() {
    list := &SingleLinkedList{}
    list.Append(11, "aa")
    list.Append(22, "bb")
    list.Append(33, "cc")
    list.Insert(5, "zz")
    list.Insert(15, "xx")
    list.Insert(15, "xx")
    list.Delete(5)
    list.Delete(33)
    list.Delete(15)
    list.Show()
}

 

posted @ 2022-05-23 20:22  ascertain  阅读(29)  评论(0编辑  收藏  举报