前些时间写了关于单链表的的基本实现,这些天看到一些关于双链表的问题,就决定再写一篇关于双链表的基本操作,其实与单链表的实现没有本质上的区别,只是增加了一个前继指针,下面看一下具体实现;
package main import ( "fmt" ) type Node struct { //节点的定义 data int Pro *Node Next *Node } type TwoList struct { //链表的定义 head *Node tail *Node length int } func (TwoList *TwoList) init(){ //初始化双链表 (*TwoList).head=nil (*TwoList).tail=nil (*TwoList).length=0 } func (TwoList *TwoList) Append (i int) bool{ //在链表尾部增加一个元素 node :=&Node{data:i} if (*TwoList).length==0{ (*TwoList).head=node node.Next=(*TwoList).tail node.Pro=nil }else if (*TwoList).length==1 { (*TwoList).tail = node (*TwoList).head.Next = (*TwoList).tail (*TwoList).tail.Pro = (*TwoList).head }else{ (*TwoList).tail.Next=node node.Pro=(*TwoList).tail (*TwoList).tail=node } (*TwoList).length++ return true } func (TwoList *TwoList) Insert (i int,n int) bool{ //在指定位置后插入一个元素 node :=&Node{data:n} if node==nil || i>(*TwoList).length ||(*TwoList).length==0{ return false } if i==0{ node.Next=(*TwoList).head (*TwoList).head.Pro=node (*TwoList).head=node }else{ cur :=(*TwoList).head for j:=1;j<i;j++{ cur=cur.Next } node.Next=cur.Next cur.Next=node node.Pro=cur node.Next.Pro=node } (*TwoList).length++ return true } func (TwoList *TwoList) Delete (i int) bool{ //删除指定位置的节点 if i>(*TwoList).length{ return false } if i==0{ (*TwoList).head=(*TwoList).head.Next (*TwoList).head.Pro=nil if (*TwoList).length==1{ (*TwoList).tail=nil } }else{ cur :=(*TwoList).head for j:=1;j<i;j++{ cur=cur.Next } cur.Next=cur.Next.Next cur.Next.Pro=cur if i==(*TwoList).length-1{ (*TwoList).tail=cur } } (*TwoList).length-- return true } func (TwoList *TwoList) Get (i int) *Node{ //获取指定位置的节点 if i>(*TwoList).length{ return nil } node :=(*TwoList).head for j:=0;j>i;j++{ node=node.Next } return node } func (TwoList *TwoList) Change(i int,n int) bool{ //改变指定位置节点的值 head:=(*TwoList).head if (*TwoList).length==0{ return false } for j:=1;j<i;j++{ head=head.Next } head.data=n return true } func (TwoList *TwoList) Print() bool{ //遍历双链表 head:=(*TwoList).head if (*TwoList).length==0{ return false } for j:=0;j<(*TwoList).length;j++{ fmt.Println(head.data) head=head.Next } return true } func main(){ list:=TwoList{} fmt.Println(list.Append(1)) fmt.Println(list.Append(2)) fmt.Println(list.Append(3)) fmt.Println(list.head) fmt.Println(list.head.Next) fmt.Println(list.tail) fmt.Println(list.Insert(1,4)) fmt.Println(list.head.Next) fmt.Println(list.Delete(1)) fmt.Println(list.head.Next) fmt.Println(list.Get(1)) list.Change(2,4) list.Print()
}
结果:
D:\gowork\src\learn\12\1>go run twolist.go
true
true
true
&{1 <nil> 0xc04204c420}
&{2 0xc04204c3e0 0xc04204c440}
&{3 0xc04204c420 <nil>}
true
&{4 0xc04204c3e0 0xc04204c420}
true
&{2 0xc04204c3e0 0xc04204c440}
&{1 <nil> 0xc04204c420}
1
4
3
有需要的大家可以根据代码和结果自行比对,有问题的欢迎留言!