十字链表保存矩阵(Java实现)
2018-04-21 本文已影响0人
thebigsilly
public class CrossLinkedMatrix {
private int col;
private int row;
private Node[] rowHead;
private Node[] colHead;
private class Node {
int x;
int y;
int elem;
Node right;
Node down;
public Node(int x, int y, int elem, Node right, Node down) {
this.x = x;
this.y = y;
this.elem = elem;
this.right = right;
this.down = down;
}
}
CrossLinkedMatrix compression(int[][] target) {
if (target == null) {
throw new UnsupportedOperationException("不支持空");
}
col = target[0].length;
row = target.length;
rowHead = new Node[row];
colHead = new Node[col];
for (int y = 0; y < row; y++) {
Node left = rowHead[y];
for (int x = 0; x < col; x++) {
if (target[y][x] != 0) {
Node node = new Node(x, y, target[y][x], null, null);
Node up = colHead[x];
if (up == null) {
colHead[x] = node;
} else {
while (up.down!=null) {
up = up.down;
}
up.down = node;
}
if (left == null) {
rowHead[y] = node;
} else {
left.right = node;
}
left = node;
}
}
}
return this;
}
CrossLinkedMatrix printColMatrix() {
if (rowHead == null) {
throw new UnsupportedOperationException("没有初始化");
}
for (int y = 0; y < row; y++) {
Node node = rowHead[y];
for (int x = 0; x < col; x++) {
if (node != null && node.x == x) {
System.out.print(node.elem + "\t");
node = node.right;
} else{
System.out.print("0\t");
}
}
System.out.println();
}
return this;
}
void printRowMatrix(){
if (colHead == null) {
throw new UnsupportedOperationException("没有初始化");
}
for (int x = 0; x < col; x++) {
Node node = colHead[x];
for (int y = 0; y < row; y++) {
if (node != null && node.y == y) {
System.out.print(node.elem + "\t");
node = node.down;
} else{
System.out.print("0\t");
}
}
System.out.println();
}
}
}