拉丁方正循环链表实现

例如:构造 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)
	}
}
    原文作者:拉丁方阵问题
    原文地址: https://blog.csdn.net/tangguangqiang/article/details/54350896
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞