如下为go 实现的双向循环列表。
package main import ( "fmt" ) type Ring struct{ prev, next *Ring val interface{} } func (r *Ring)init() *Ring { r.prev = r r.next = r return r } func (r *Ring)iterate_clockward(){ cur := r.next if cur == r { fmt.Println("clockward sigle node ") return } for cur != r { fmt.Println("cur ", cur.val) cur = cur.next } } func (r *Ring)iterate_counterclock(){ cur := r.prev if cur == r { fmt.Println("counterclock sigle node") return } for cur != r { fmt.Println("cur ", cur.val) cur = cur.prev } } //insert in the first place, r as the head func (r *Ring)insert(a interface{}){ node := new(Ring) node.val = a next := r.next node.next = next node.prev = r r.next = node next.prev = node } func (r *Ring)unlink(a interface{}){ cur := r.next if cur == r { fmt.Println("single node") return } for cur != r { if cur.val == a { prev := cur.prev next := cur.next prev.next = next next.prev = prev return } cur = cur.next } } func (r *Ring)len() int { cur := r.next if cur == r { fmt.Println("single node") return 0 } i := 0 for cur != r { i++ cur = cur.next } return i } func main(){ r := new(Ring) r.init() for i := 0; i < 5; i++ { r.insert(i) } r.iterate_clockward() fmt.Println("before unlink len", r.len()) r.unlink(2) fmt.Println("after unlink len", r.len()) fmt.Println("counter clock") r.iterate_counterclock() }
打印结果如下:
cur 4
cur 3
cur 2
cur 1
cur 0
before unlink len 5
after unlink len 4
counter clock
cur 0
cur 1
cur 3
cur 4
标签:node,golang,cur,fmt,next,链表,双向,Ring,prev From: https://www.cnblogs.com/wallywl/p/16739125.html