Go language single linked list implementation method

  • 2020-05-26 09:19:43
  • OfStack

This article illustrates the implementation of single linked list in Go language. Share with you for your reference. The details are as follows:

1. singlechain.go code is as follows:

//////////
// Singly linked lists -- The linear table
package singlechain
// Define the node
type Node struct {
    Data int
    Next *Node
}
/*
* Returns the first 1 A node
* h The first node
 */
func GetFirst(h *Node) *Node {
    if h.Next == nil {
        return nil
    }
    return h.Next
}
/*
* Returns the last 1 A node
* h The first node
 */
func GetLast(h *Node) *Node {
    if h.Next == nil {
        return nil
    }
    i := h
    for i.Next != nil {
        i = i.Next
        if i.Next == nil {
            return i
        }
    }
    return nil
}
// Take the length of the
func GetLength(h *Node) int {
    var i int = 0
    n := h
    for n.Next != nil {
        i++
        n = n.Next
    }
    return i
}
// insert 1 A node
//h: The first node
//d: The node to insert
//p: The position to insert
func Insert(h, d *Node, p int) bool {
    if h.Next == nil {
        h.Next = d
        return true
    }
    i := 0
    n := h
    for n.Next != nil {
        i++
        if i == p {
            if n.Next.Next == nil {
                n.Next = d
                return true
            } else {
                d.Next = n.Next
                n.Next = d.Next
                return true
            }
        }
        n = n.Next
        if n.Next == nil {
            n.Next = 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 n.Next != nil {
        i++
        n = n.Next
        if i == p {
            return n
        }
    }
    return nil
}

2. main.go code is as follows:
package main
import "fmt"
import "list/singlechain"
func main() {
    // Initialize the 1 Head node
    var h singlechain.Node
    // Insert into the list 10 An element
    for i := 1; i <= 10; i++ {
        var d singlechain.Node
        d.Data = i
        singlechain.Insert(&h, &d, i)
        fmt.Println(singlechain.GetLoc(&h, i))
    }
    fmt.Println(singlechain.GetLength(&h))
    fmt.Println(singlechain.GetFirst(&h))
    fmt.Println(singlechain.GetLast(&h))
    fmt.Println(singlechain.GetLoc(&h, 6))
}

I hope this article has been helpful to your programming of Go language.


Related articles: