package main
import (
"fmt"
)
type Node struct {
next *Node
Value any
}
type List struct {
head *Node
}
func NewList() *List {
return &List{&Node{}} // 头结点不存值
}
func (l *List) Insert(value any) { // 头插法
n := &Node{Value: value}
n.next = l.head.next
l.head.next = n
}
func (l *List) Delete(value any) {
head := l.head
//for head != nil { // 头结点存储值时
// if head.Value != value {
// break
// }
// head = head.next
//}
prev, cur := head, head
for cur != nil {
if cur.Value == value {
prev.next = cur.next
} else {
prev = cur
}
cur = cur.next
}
}
func (l *List) Update(oldValue, newValue any) {
for cur := l.head; cur != nil; cur = cur.next {
if cur.Value == oldValue {
cur.Value = newValue
}
}
}
func (l *List) Search(value any) (exist bool) {
for cur := l.head; cur != nil; cur = cur.next {
if cur.Value == value {
return true
}
}
return false
}
func PrintList(list *List) {
fmt.Print("[ ")
for head := list.head; head != nil; head = head.next {
//if head.Value != nil {
fmt.Print(head.Value, " ")
//}
}
fmt.Println("]")
}
可以在有序的链表的值域中放一个数组,同时使得数组中的值也是有序的,那么数组&链表的数据结构,既有了数组的特性,又有了链表的特性。