【JAVA】将已给的邻接矩阵转换为邻接表并输出 #前插(头插)#后插(尾插)

题目如下

选择用前插(头插)或后插(尾插)的方式得到如下邻接矩阵的邻接表并输出
在这里插入图片描述
输出方式例如
在这里插入图片描述先上代码

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();
		}
	}
}

有关邻接表的内容如下图
在这里插入图片描述
哪里有疑问或者我哪里写的不对大家可以评论我呀
觉得写得不错的话就给我点点赞吧~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值