1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
使用循環鏈表構建:
package main
import (
"fmt"
)
//結點結構
type Node struct {
data int
next *Node
}
//建立循環鏈表
func createList(len int)*Node {
if len<1 {
return nil
}
phead:=new(Node)
phead.data=1
phead.next=nil
q:=phead
for i:=2;i<=len;i++ {
pnew:=new(Node)
pnew.data=i
q.next=pnew
q=pnew
}
q.next=phead
return q //返回尾指針
}
//判斷是否爲空
func isempty(list *Node) bool {
if list.next==nil {
return true
}else {
return false
}
}
//遍歷鏈表
func traverse(list *Node) {
if isempty(list) {
return
}
for p:=list.next;p!=list;p=p.next{
fmt.Printf("%3d",p.data)
}
fmt.Printf("%3d\n",list.data)
}
//循環遍歷鏈表,打印拉丁方正
func printList(list *Node){
p:=list
traverse(p)
p=p.next
for p!=list {
traverse(p)
p=p.next
}
}
func main() {
list:=createList(3)
if list!=nil {
printList(list)
//traverse(list)
}
}