稀疏数组的链式存储实现(使用单向链表)
(1)链表类
public class LinkedList {
public int row;
public int column;
public int data;
public LinkedList next;
public LinkedList() {
}
public LinkedList(int row, int column, int data) {
this.row = row;
this.column = column;
this.data = data;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
@Override
public String toString() {
return "LinkedList{" +
"row=" + row +
", column=" + column +
", data=" + data +
'}';
}
}
(2)业务实现
public class LinkedListSparseArray {
private LinkedList head = new LinkedList(0,0,0);
public int[][] createArray(){
int[][] array = new int[11][11];
array[1][1] = 1;
array[2][2] = 3;
array[3][3] = 9;
array[9][9] = 81;
for (int[] row : array) {
for (int val : row) {
System.out.printf("%d\t", val);
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (array[i][j] != 0) {
sum++;
}
}
}
System.out.println("有效数据个数:" + sum);
return array;
}
public void arrayTransferLinkedList(int[][] paramArray,LinkedList linkedList){
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (paramArray[i][j] != 0) {
linkedList.setRow(i);
linkedList.setColumn(j);
linkedList.setData(paramArray[i][j]);
LinkedList temp = head;
while (true){
if(temp.next == null){
break;
}
temp = temp.next;
}
temp.next = linkedList;
linkedList = new LinkedList();
}
}
}
}
public void showNode() {
if (head.next == null) {
System.out.println("这是空链表,查看所有元素完毕");
}
LinkedList temp = head.next;
while (true) {
if (temp == null) {
break;
} else {
System.out.println(temp);
}
temp = temp.next;
}
}
}
(3)测试
public class TestLinkedListSparseArray {
public static void main(String[] args) {
LinkedListSparseArray linkedListSparseArray = new LinkedListSparseArray();
LinkedList LinkedListParam = new LinkedList();
int[][] array = linkedListSparseArray.createArray();
linkedListSparseArray.arrayTransferLinkedList(array,LinkedListParam);
linkedListSparseArray.showNode();
}
}