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();
}
}
}
十字链表保存矩阵(Java实现)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 链结点:在链表中,每个数据项都被包含在"链结点"(Link)中.一个链结点是某个类的对象,这个类可以叫Link.而...
- 本章内容主要来自算法(第四版) Robert Sedgewick著 1.3小节 栈(后进先出)的基本功能 队列(先...
- 本文行文思路结构 一. 线性表 部分定义和解释见下面链接:http://blog.csdn.net/menglan...