基于邻接表的新顶点的增加
作者:互联网
描述
给定一个无向图,在此无向图中增加一个新顶点。
输入
多组数据,每组m+2行。第一行有两个数字n和m,代表有n个顶点和m条边。顶点编号为1到n。第二行到第m+1行每行有两个数字h和k,代表边依附的两个顶点。第m+2行有一个数字f,代表新插入的顶点编号。当n和m都等于0时,输入结束
输出
每组数据输出n+1行。为增加顶点后的邻接表。每两个数字之间用空格隔开。
输入样例 1
3 2 1 2 2 3 4 2 1 1 2 4 0 0
输出样例 1
1 2 2 3 1 3 2 4 1 2 2 1 4
#include<iostream>
#define OK 1
#define ERROR -1
#define MVNum 100
using namespace std;
typedef struct VNode{
int data;
struct VNode *next;
}VNode,*NodeList;
typedef struct{
NodeList V[MVNum];
int vexnum,arcnum;
}ALGraph;
int CreateUDG(ALGraph &G,int vexnum,int arcnum){
G.vexnum = vexnum;
G.arcnum = arcnum;
for(int i=1;i<=vexnum; i ++){
G.V[i] = new VNode;
G.V[i]->next = NULL;
G.V[i]->data = i;
}
for(int i=0;i<arcnum;i++){
int v1,v2;
cin>>v1>>v2;
NodeList p1 =new VNode;
p1->data =v2;
p1->next =G.V[v1]->next;
G.V[v1]->next = p1;
NodeList p2 =new VNode;
p2->data = v1;
p2->next = G.V[v2]->next;
G.V[v2]->next = p2;
}
return OK;
}
int InsertVex(ALGraph &G){
int data;
cin>>data;
G.vexnum++;
G.V[G.vexnum] = new VNode;
G.V[G.vexnum]->data = data;
G.V[G.vexnum]->next = NULL;
return OK;
}
int PrintAL(ALGraph G){
for(int i=1;i<=G.vexnum;i++){
NodeList p =G.V[i];
while(p->next){
cout<<p->data<<" ";
p = p->next;
}
cout<<p->data<<endl;
}
return OK;
}
int main(){
int vexnum,arcnum;
while(cin>>vexnum>>arcnum&&vexnum!=0&&arcnum!=0){
ALGraph G;
CreateUDG(G,vexnum,arcnum);
InsertVex(G);
PrintAL(G);
}
return 0;
}
标签:vexnum,基于,arcnum,int,next,邻接,顶点,VNode,data 来源: https://blog.csdn.net/m0_53354306/article/details/122665191