题目如下
选择用前插(头插)或后插(尾插)的方式得到如下邻接矩阵的邻接表并输出
输出方式例如
先上代码
class Node{ //无论是表结点还是头结点都是用同一个类即可
String data; //数据域
Node next; //相当于指针域,指向下一个结点
public void head(Node newnode) { //前插方式
newnode.next = this.next; //要插入的结点的下一个结点指向调用该函数的头结点的原本的下一个结点
this.next = newnode; //将头结点的下一个结点指向要插入的结点
}
public void tail(Node newnode) { //后插方式
Node test = this; //新建一个结点指向调用该函数的头结点
while(true) {
if(test.next == null) { //如果test结点没有下一个结点
test.next = newnode; //将要插入的结点插入到该test结点后
break; //然后退出循环
}
else
test = test.next; //如果test结点有下一个结点,将test等于test的下一个结点
}
}
public void printlist() { //输出邻接表
Node test = this; //新建一个test结点,指向调用该函数的头结点
System.out.print(test.data + " "); //输出该头结点的数据域(+""使为了使得test的数据域转换为String类型)
while((test = test.next) != null) { //使test等于test的下一个结点(这样就算条件不成立,test还可以一直更新)
System.out.print(test.data + " "); //若test不为空,输出test的数据域
}
System.out.println();
}
}
public class Adjacency_list_right {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int[][] adjMatrix = new int[][]{{0,1,0,1,0,0,0,0},
{1,0,1,0,0,0,0,0},
{0,1,0,1,1,0,0,0},
{1,0,1,0,0,0,0,0},
{0,0,1,0,0,1,1,0},
{0,0,0,0,1,0,0,1},
{0,0,0,0,1,0,0,1},
{0,0,0,0,0,1,1,0}};
Node[] AdjList = new Node[adjMatrix.length]; //创建头结点数组
for(int i = 0; i < adjMatrix.length; i++) { //头结点初始化
AdjList[i] = new Node();
AdjList[i].data = "V" + (i + 1);
AdjList[i].next = null;
}
System.out.print("请选择插入方式(1:前插;2:后插):"); //选择插入方式
int choice = input.nextInt();
input.close();
int i = 0, j = 0;
for(i = 0; i < adjMatrix.length; i++) {
for(j = 0; j < adjMatrix.length; j++) {
if(adjMatrix[i][j] == 1) { //如果邻接矩阵中元素为1,则说明i与j相应的结点邻接
Node newnode = new Node();
newnode.data = j + "";
if(choice == 1)
AdjList[i].head(newnode);
else
AdjList[i].tail(newnode);
}
}
System.out.print(i + " ");
AdjList[i].printlist();
}
}
}
有关邻接表的内容如下图
哪里有疑问或者我哪里写的不对大家可以评论我呀
觉得写得不错的话就给我点点赞吧~