SoFunction
Updated on 2025-03-03

Go language single linked list implementation method

//////////
//Single-linked list -- Linear table
package singlechain
//Define node
type Node struct {
    Data int
    Next *Node
}
/*
* Return to the first node
* h head node
 */
func GetFirst(h *Node) *Node {
    if == nil {
        return nil
    }
    return
}
/*
* Return to the last node
* h head node
 */
func GetLast(h *Node) *Node {
    if == nil {
        return nil
    }
    i := h
    for != nil {
        i =
        if == nil {
            return i
        }
    }
    return nil
}
//Take the length
func GetLength(h *Node) int {
    var i int = 0
    n := h
    for != nil {
        i++
        n =
    }
    return i
}
//Insert a node
//h: Header node
//d: The node to be inserted
//p: The location to be inserted
func Insert(h, d *Node, p int) bool {
    if == nil {
        = d
        return true
    }
    i := 0
    n := h
    for != nil {
        i++
        if i == p {
            if == nil {
                = d
                return true
            } else {
                =
                =
                return true
            }
        }
        n =
        if == nil {
            = d
            return true
        }
    }
    return false
}
//Fetch the specified node
func GetLoc(h *Node, p int) *Node {
    if p < 0 || p > GetLength(h) {
        return nil
    }
    var i int = 0
    n := h
    for != nil {
        i++
        n =
        if i == p {
            return n
        }
    }
    return nil
}