package main
import (
"errors"
"fmt"
)
type Node struct {
key int
value string
next *Node
}
func newNode(key int, value string)(newNode *Node) {
newNode = &Node{
key :key,
value: value,
}
newNode.next = newNode
return newNode
}
func addNode(list ,newNode *Node) {
newNode.next = list.next
list.next = newNode
}
func showList(list *Node) {
if list == nil {
fmt.Println("链表为空")
return
}
tmp := list
for {
fmt.Printf("key:%d,value:%s",tmp.key,tmp.value)
tmp = tmp.next
if tmp == list {
break
}
}
fmt.Println()
}
func delByValue(list *Node, key int) (reslist *Node,err error){
reslist = list
tmp := list
i := 1
for {
if tmp.next.key == key {
if tmp.next== list {
reslist = list.next
}
tmp.next = tmp.next.next
return
}
tmp = tmp.next
if tmp == list {
break
}
i++
}
err = errors.New("链表中没有对于的key")
return
}
func main() {
node1 := newNode(10,"100")
node2 := newNode(20,"200")
node3 := newNode(30,"300")
node4 := newNode(40,"400")
addNode(node1,node2)
showList(node1)
addNode(node1,node3)
showList(node1)
addNode(node1,node4)
showList(node1)
node1, err := delByValue(node1,10)
if err != nil{
fmt.Println(err)
return
}
fmt.Println("===================")
showList(node1)
}
|