目标:
- 实现一个循环单链表
- 实现一个循环双链表
代码实现:
package main
import (
"fmt"
"time"
)
// 单向链表结点
type LNode struct {
data interface{}
next *LNode
}
func main() {
// 循环单链表遍历
LoopList := getLoopList()
tmpLoopList := LoopList
for tmpLoopList != nil {
fmt.Println(tmpLoopList.data)
tmpLoopList = tmpLoopList.next
time.Sleep(time.Second)
}
}
func getLoopList() *LNode {
node := new(LNode)
node.data = 0
first := node
for i:=1; i<10; i++ {
temp := new(LNode)
temp.data = i
node.next = temp
node = temp
}
node.next = first
return first
}
package main
import (
"fmt"
"time"
)
// 双向链表结点
type RNode struct {
data interface{}
prev *RNode
next *RNode
}
func main() {
// 循环双链表
ring := getRing()
// 顺时针遍历
tmpRing := ring
for tmpRing != nil {
fmt.Println(tmpRing.data)
tmpRing = tmpRing.next
time.Sleep(time.Second)
}
//// 逆时针遍历
//tmpRing2 := ring
//for tmpRing2 != nil {
// fmt.Println(tmpRing2.data)
// tmpRing2 = tmpRing2.prev
// time.Sleep(time.Second)
//}
}
func getRing() *RNode {
node := new(RNode)
node.data = 0
first := node
for i := 1; i < 10; i++ {
temp := new(RNode)
temp.data = i
temp.prev = node
node.next = temp
node = temp
}
node.next = first
first.prev = node
return first
}