Bidirectional linked list of a Go language implementation
package main
import "fmt"
// Define node information
type dNode struct {
id int
name string
pre *dNode
next *dNode
}
// Insert the tail node
func dInsertTail(head, newNode *dNode) {
// Define a temporary walk variable
temp := head
for {
if temp.next == nil{
break // Walk to the end of the list and jump out of the loop to insert data
}
temp = temp.next
}
// Adding a tail is relatively simple
temp.next = newNode
newNode.pre = temp
}
// The header inserts the node
func dInsertHead(head, newNode *dNode) {
temp := head
// First join the two chains of the new node to the list
newNode.next = temp.next
newNode.pre = temp
// Disconnect the old connection to the new connection
temp.next = newNode
temp.next.pre = newNode
}
// Insert nodes sequentially
func dInsertSort(head, newNode *dNode){
temp := head
for {
if temp.next == nil{
newNode.next = temp.next
newNode.pre = temp
temp.next = newNode
//temp.next.pre = newNode
break
} else if temp.next.id >= newNode.id {
newNode.next = temp.next
newNode.pre = temp
temp.next = newNode
temp.next.pre = newNode
break
}
temp = temp.next
}
}
// Delete the node in the header
func dDeleteHead(head *dNode){
if head.next == nil{
return
}else {
head.next = head.next.next
}
}
// Delete the node
func dDeleteTail(head *dNode){
temp := head
for {
if temp.next == nil {
return
} else if temp.next.next == nil{
// Delete a node
temp.next = nil
break
}
temp = temp.next
}
}
// Delete the specified node
func dDeleteNode(head, node * dNode){
temp := head
for {
if temp.next == nil {
return
}else if temp.next.id == node.id {
temp.next = temp.next.next
temp.next.pre = temp
break
}
temp = temp.next
}
}
// Displays list elements
func dList(head *dNode){
temp := head
if temp.next == nil {
fmt.Println("Linked list is empty")
return
}
for {
// Notice that all I'm doing here is operating on the next node in the list from the current node
fmt.Printf("%d %s --> ", temp.next.id, temp.next.name)
temp = temp.next
if temp.next == nil{
break}}}func main(a){
head := &dNode{}
node1 := &dNode{
id: 0,
name: "number1",
pre: nil,
next: nil,
}
node2 := &dNode{
id: 1,
name: "number2",
pre: nil,
next: nil,
}
node3 := &dNode{
id: 2,
name: "number3",
pre: nil,
next: nil,
}
node4 := &dNode{
id: 3,
name: "number4",
pre: nil,
next: nil,
}
dInsertHead(head, node1)
dInsertTail(head, node3)
dInsertSort(head, node2)
dInsertSort(head, node4)
dDeleteHead(head)
dDeleteTail(head)
dDeleteNode(head, node2)
dList(head)
}
Copy the code