1、带头节点的链表逆置
//链表逆置
type Node struct{
data int
next *Node
}
func Reversenode(list *Node) *Node {
if list==nil || list.next==nil || list.next.next==nil{
return nil
}
p:=list.next
list.next=nil
var q *Node
for p!=nil{
q=p.next
p.next=list.next
list.next=p
p=q
}
return list
}
func TestReversenode(t *testing.T) {
head:=new(Node)
l1:=new(Node)
l1.data=1
l2:=new(Node)
l2.data=2
l3:=new(Node)
l3.data=3
l4:=new(Node)
l4.data=4
l5:=new(Node)
l5.data=5
head.next=l1
l1.next=l2
l2.next=l3
l3.next=l4
l4.next=l5
l5.next=nil
for p:=head.next;p!=nil;p=p.next{
fmt.Print(p.data)
}
Reversenode(head)
fmt.Print("\n")
for p:=head.next;p!=nil;p=p.next{
fmt.Print(p.data)
}
}
2、删除节点
//删除节点
func Findpri(list *Node, val int) *Node{ //找前驱
if list==nil || list.next==nil{
return nil
}
for p:=list;p.next!=nil;p=p.next{
if p.next.data==val{
return p
}
}
return nil
}
func DeleteNode(list *Node, val int) bool{
if list==nil || list.next==nil{
return false
}
p:=Findpri(list,val)
if p==nil{
fmt.Println("not exist")
return false
}
q:=p.next
p.next=q.next
return true
}
func TestDeleteNode(t *testing.T) {
head:=new(Node)
l1:=new(Node)
l1.data=1
l2:=new(Node)
l2.data=2
l3:=new(Node)
l3.data=3
l4:=new(Node)
l4.data=4
l5:=new(Node)
l5.data=5
head.next=l1
l1.next=l2
l2.next=l3
l3.next=l4
l4.next=l5
l5.next=nil
for p:=head.next;p!=nil;p=p.next{
fmt.Print(p.data)
}
DeleteNode(head,1)
fmt.Print("\n")
for p:=head.next;p!=nil;p=p.next{
fmt.Print(p.data)
}
}