拉丁方正循環鏈表實現

例如:構造 NXN 階的拉丁方陣(2<=N<=9),使方陣中的每一行和每一列中數字1到N只出現一次。如N=4時:
  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)
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章