问题介绍
传送门
n阶方阵中,恰有 n 种不同的元素,每一种不同的元素在同一行或同一列里只出现一次。
解
应用循环列表,不断移动头节点位置构造方阵的行(使每个元素错开输出),移动n-1次。
循环列表实现:(此处仅实现初始化)
public class CircleList {
public Node headNode;
public int listLength;
public CircleList(int length) {
Node head = new Node();
Node tempP = head;
Node tempQ = head;
int count = 1;
while (count <= length) {
tempQ = new Node();
tempQ.data = count++;
tempQ.pre = tempP;
tempQ.next = tempP.next;
tempP.next = tempQ;
tempP = tempQ;
listLength++;
}
tempQ.next = head.next;
head.next.pre = tempQ;
headNode = tempQ.next;
}
public Node getHeadNode() {
System.out.println(headNode.data);
return headNode;
}
public void printList() {
Node curNode = headNode;
int count = 1;
while (this.listLength >= count) {
System.out.println(curNode.data);
curNode = curNode.next;
count++;
}
}
}
public class Node {
int data;
Node pre;
Node next;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
测试:
public class LatinSquare {
public static void main(String[] args) {
while (true){
System.out.println("请输入矩阵次方");
Scanner sc = new Scanner(System.in);
if (sc.hasNextLine()) {
String x = sc.nextLine();
System.out.println(x);
CircleList list = new CircleList(Integer.valueOf(x));
int count = 1;
while (count <= Integer.valueOf(x)){
System.out.println("方阵第"+count+"行:");
list.printList();
//移动头节点
list.headNode = list.headNode.getNext();
count++;
}
list.headNode = null;
continue;
} else {
System.out.println("输入错误,请重新输入");
}
}
}
}