package main
import (
"fmt"
"math/rand"
"time"
)
type Comparable[T any] interface {
Compare(T) int
}
type Node[T any] struct {
next *Node[T]
Value Comparable[T]
}
type List[T any] struct {
head *Node[T]
}
func NewList[T Comparable[T]]() *List[T] {
return &List[T]{&Node[T]{}} // 头结点不存值
}
func (list *List[T]) Insert(value Comparable[T]) {
n := &Node[T]{Value: value}
prev, cur := list.head, list.head.next
for cur != nil && cur.Value.Compare(n.Value.(T)) <= 0 {
prev = cur
cur = cur.next
}
n.next = prev.next
prev.next = n
}
type MyInt int
func (m MyInt) Compare(m1 MyInt) int {
return int(m - m1)
}
func main() {
rand.Seed(time.Now().Unix())
l := NewList[MyInt]()
for i := 0; i < 100; i++ {
l.Insert(MyInt(rand.Intn(1000)))
}
l.Insert(MyInt(456))
l.Insert(MyInt(789))
l.Delete(MyInt(456))
l.Delete(MyInt(789))
l.Print()
}
func (list *List[T]) Delete(value T) {
head := list.head
//for head != nil { // 头结点存储值时
// if head.Value != value {
// break
// }
// head = head.next
//}
prev, cur := head, head.next
for cur != nil {
if cur.Value.Compare(value) == 0 {
prev.next = cur.next
} else {
prev = cur
}
cur = cur.next
}
}
func (list *List[T]) Update(oldValue, newValue Comparable[T]) {
for cur := list.head; cur != nil; cur = cur.next {
if cur.Value == oldValue {
cur.Value = newValue
}
}
}
func (list *List[T]) Search(value T) (exist bool) {
for cur := list.head.next; cur != nil; cur = cur.next {
if cur.Value.Compare(value) == 0 {
return true
}
}
return false
}
func (list *List[T]) Print() {
fmt.Print("[ ")
for head := list.head; head != nil; head = head.next {
//if head.Value != nil {
fmt.Print(head.Value, " ")
//}
}
fmt.Println("]")
}
search——sorted single list
于 2022-12-06 14:39:56 首次发布