修改下列代码要求如下:每组数据输出n-1行。为删除顶点后的邻接表。每两个数字之间用空格隔开。代码如下:#include<iostream> #include<string> #include<algorithm> #include<vector> #include<set> #include<map> using namespace std;typedef struct LNode {int data;struct LNode* next; }*linklist, LNode; typedef struct {int vexnum;int arcnum;linklist VList; }ALGragh; void CreateUDG(ALGragh& G, int n, int m) {G.arcnum = m;G.vexnum = n;G.VList = new LNode[n + 1];for (int i = 1; i <= n; i++){G.VList[i].data = i;G.VList[i].next = NULL;}int h, k;for (int i = 0; i < m; i++){cin >> h >> k;linklist p = new LNode, q = new LNode;p->data = h;p->next = G.VList[k].next;G.VList[k].next = p;q->data = k;q->next = G.VList[h].next;G.VList[h].next = q;} } void PrintGraph(ALGragh G) {for (int i = 1; i <= G.vexnum; i++){linklist p = &G.VList[i];while (p->next){cout << p->data << ' ';p = p->next;}cout << p->data << endl;} } void DeleteVex(ALGragh& G) {int h, k;cin >> h >> k;for (int i = 1; i <= G.vexnum ; i++){linklist p = &G.VList[i];if (i == h){if (p->next){if (p->next->data == k)p->next = p->next->next;}}if (i == k){if (p->next){if (p->next->data == h)p->next = p->next->next;}}} }
时间: 2024-03-09 19:47:22 浏览: 68
C++实现邻接表顶点的删除
修改后的代码如下所示:
```
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
using namespace std;
typedef struct LNode {
int data;
struct LNode* next;
}*linklist, LNode;
typedef struct {
int vexnum;
int arcnum;
linklist VList;
}ALGragh;
void CreateUDG(ALGragh& G, int n, int m) {
G.arcnum = m;
G.vexnum = n;
G.VList = new LNode[n + 1];
for (int i = 1; i <= n; i++){
G.VList[i].data = i;
G.VList[i].next = NULL;
}
int h, k;
for (int i = 0; i < m; i++){
cin >> h >> k;
linklist p = new LNode, q = new LNode;
p->data = h;
p->next = G.VList[k].next;
G.VList[k].next = p;
q->data = k;
q->next = G.VList[h].next;
G.VList[h].next = q;
}
}
void PrintGraph(ALGragh G) {
for (int i = 1; i <= G.vexnum; i++){
linklist p = &G.VList[i];
while (p->next){
cout << p->data << ' ';
p = p->next;
}
cout << p->data << endl;
}
}
void DeleteVex(ALGragh& G) {
int h, k;
cin >> h >> k;
linklist p = G.VList[h].next;
while (p) {
if (p->data == k) {
G.VList[h].next = p->next;
break;
}
p = p->next;
}
p = G.VList[k].next;
while (p) {
if (p->data == h) {
G.VList[k].next = p->next;
break;
}
p = p->next;
}
}
int main() {
int n, m;
cin >> n >> m;
ALGragh G;
CreateUDG(G, n, m);
for (int i = 1; i <= n; i++) {
ALGragh temp = G;
DeleteVex(temp);
PrintGraph(temp);
}
return 0;
}
```
修改后的代码中,新增了一个 `main()` 函数,其中包含了循环删除每个顶点的代码。在 `DeleteVex()` 函数中,修改了删除顶点的逻辑,使其可以正确删除指定顶点,并且同时更新相邻顶点的邻接表。在每次删除顶点后,调用 `PrintGraph()` 函数输出邻接表即可。
阅读全文