Go language single Link list realization method _golang

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.