This article illustrates the way of the Go Language single link list implementation. Share to everyone for your reference. Specifically as follows:
1. The Singlechain.go code is as follows:
Copy Code code as follows:
//////////
Single linked list--linear table
Package Singlechain
Defining nodes
Type Node struct {
Data int
Next *node
}
/*
* Return to the first node
* H-head node
*/
Func GetFirst (H *node) *node {
if H.next = = Nil {
return Nil
}
Return H.next
}
/*
* Return to last node
* H-head 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 length
Func getlength (h *node) int {
var i int = 0
N: = h
For N.next!= Nil {
i++
n = n.next
}
return I
}
Insert a Node
H: Head 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
}
Remove 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. The Main.go code is as follows:
Copy Code code as follows:
Package Main
Import "FMT"
Import "List/singlechain"
Func Main () {
Initializes a header node.
var h singlechain. Node
Insert 10 elements into a linked list
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 will help you with your go language program.