单链表参考视频:https://www.bilibili.com/video/BV1ME411Y71o?p=352&spm_id_from=pageDriver
package main
import "fmt"
type SinglyListNode struct {
val int
next *SinglyListNode
}
func AddLastNode(header *SinglyListNode, value int) bool {
temp := header
for temp.next != nil {
temp = temp.next
}
temp.next = &SinglyListNode{val: value}
return true
}
func AddSortNode(header *SinglyListNode, value int) bool {
temp := header
for temp.next != nil && temp.next.val <= value {
temp = temp.next
}
node := &SinglyListNode{val: value}
node.next = temp.next
temp.next = node
return true
}
func DeleteList(header *SinglyListNode, value int) bool {
temp := header
for temp.next != nil && temp.next.val != value {
temp = temp.next
}
if temp.next == nil {
return false
}
temp.next = temp.next.next
return true
}
func ShowList(header *SinglyListNode) {
temp := header.next
fmt.Print("header")
for temp.next != nil {
fmt.Print("->", temp.val)
temp = temp.next
}
fmt.Println()
}
func main() {
header := SinglyListNode{}
for i := 0; i < 10; i++ {
AddLastNode(&header, i)
}
ShowList(&header)
for i := 20; i > 10; i-- {
AddSortNode(&header, i)
}
ShowList(&header)
fmt.Println(DeleteList(&header, 5))
ShowList(&header)
fmt.Println(DeleteList(&header, 5))
ShowList(&header)
}
双向链表参考视频:https://www.bilibili.com/video/BV1ME411Y71o?p=356&spm_id_from=pageDriver
package main
import "fmt"
func main() {
header2 := DoublyListNode{}
for i := 0; i < 10; i++ {
AddLastNode2(&header2, i)
}
ShowList2(&header2)
for i := 20; i > 10; i-- {
AddSortNode2(&header2, i)
}
ShowList2(&header2)
fmt.Println(DeleteList2(&header2, 5))
ShowList2(&header2)
fmt.Println(DeleteList2(&header2, 5))
ShowList2(&header2)
}
type DoublyListNode struct {
val int
pre *DoublyListNode
next *DoublyListNode
}
func AddLastNode2(header *DoublyListNode, value int) bool {
temp := header
for temp.next != nil {
temp = temp.next
}
node := &DoublyListNode{val: value}
temp.next = node
node.pre = temp
return true
}
func AddSortNode2(header *DoublyListNode, value int) bool {
temp := header
for temp.next != nil && temp.val <= value {
temp = temp.next
}
node := &DoublyListNode{val: value}
temp.pre.next = node
node.pre = temp.pre
node.next = temp
temp.pre = node
return true
}
func DeleteList2(header *DoublyListNode, value int) bool {
temp := header
for temp.next != nil && temp.val != value {
temp = temp.next
}
if temp.next == nil {
return false
}
temp.pre.next = temp.next
temp.next.pre = temp.pre
return true
}
func ShowList2(header *DoublyListNode) {
temp := header.next
fmt.Print("header")
for temp.next != nil {
fmt.Print("->", temp.val)
temp = temp.next
}
fmt.Println()
}
循环链表懒得写了https://www.bilibili.com/video/BV1ME411Y71o?p=359&spm_id_from=pageDriver
|