# 利用Java如何实现将二维数组转化为链式储存

## 代码实现

```/**
* 模拟结点
*/
public class SingleNode {
/**
* @row 行号
* @column 列号
* @num 值
*/
public int row;
public int colunm;
public int num;
/**
*next域：指向下一个结点
*/
public SingleNode next;

public SingleNode(int row, int colunm, int num) {
this.row = row;
this.colunm = colunm;
this.num = num;
}

@Override
public String toString() {
return "SingleNode{" + "row=" + row + ", colunm=" + colunm + ", num=" + num + "}";
}
}
```

```public class SingleLinkList {
//头节点
//通过构造行数初始化头节点
}

/**
* 添加结点(追加在链表的尾端)
*/
while(true){
if (temp.next == null) {
//如果这个结点的next域为空就跳出while循环
break;
}
//将下一个结点赋值给temp
temp = temp.next;
}
temp.next= SingleNode;
}
/**
* 遍历单项链表
*/
public void show(){
System.out.println("当前链表为空");
return;
}
while (true){
if (temp.next == null){
break;
}
temp = temp.next;
System.out.println(temp);
}
}

/**
* 将链表还原成二维数组
* @return array还原后的二维数组
*/
public int[][] backToArray(){
//头结点中存储着原数组的行数和列数
//通过这两个值创建二维数组
while (true){
if (temp.next == null){
break;
}
temp = temp.next;
//每遍历一个结点就还原一个数据
array[temp.row][temp.colunm] = temp.num;
}
return array;
}
}
```
```public class ArrayToLink {
public static void main(String[] args) {
int[][] array = new int[4][5];
//初始化二维数组
array[0][2] = 1;
array[1][1] = 2;
array[2][3] = 3;

System.out.println("========普通数组========");
//遍历二维数组
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j]!=0){
count++;
}
System.out.print(array[i][j] + " ");
}
System.out.println();
}

//将数组转化成链式存储
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] != 0){
//当数字不为0时视为有效值就创建一个结点并添加到链表尾部
}
}
}
System.out.println("========转化后的链表========");
//遍历单向链表
list.show();

int[][] returnArray = list.backToArray();
//遍历还原后的二维数组
System.out.println("========还原后的数组========");
for (int i = 0; i < returnArray.length; i++) {
for (int j = 0; j < returnArray[i].length; j++) {
System.out.print(returnArray[i][j] + " ");
}
System.out.println();
}
}
}

```