search——sorted single list

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("]")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

metabit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值