代码:
package Matriix;
import java.util.Scanner;
public class Demo1 {
//将一个稀疏矩阵从一个二维数组转变成只包含非零结点的多链表
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int V = scan.nextInt();
int E = scan.nextInt();
boolean[][] adj = new boolean[V][V];
Node ad[] = new Node[E];
for(int i=0;i<V;i++){
for(int j=0;j<V;j++){
adj[i][j] = false;
}
}
//初始化一个稀疏矩阵
for(int i=0;i<E;i++){
String input = scan.next();
int x = Integer.parseInt(input.substring(1, 2));
int y = Integer.parseInt(input.substring(3, 4));
adj[x][y] = true;
adj[y][x] = true;
}//i,j即为点坐标
//转化
int count = 0;
for(int i=0;i<V;i++){
for(int j=0;j<count;j++){
if(adj[i][j]){//(i,j)
ad[i] = new Node(j,ad[i]);
ad[j] = new Node(i,ad[j]);
}
}
count++;
}
//输出
for(int i=0;i<V;i++){
for(Node temp=ad[i];temp!=null;temp=temp.next){
System.out.print(temp.val+" ");
}
System.out.println();
}
}
static class Node{
int val;
Node next;
public Node(int val,Node next){
this.val = val;
this.next = next;
}
}
}