【发布时间】:2015-10-01 14:29:23
【问题描述】:
首先,我是图的新手。在研究了图的概念之后。我想到了用c ++实现。搜索实现的时候觉得代码很难看懂,所以想自己实现。
以下是我尝试过的代码:
#include<iostream>
using namespace std;
struct Node {
int data;
Node *link;
};
//creating array of nodes
struct Node *array[10];
//creating array of head pointers to point each of the array node.
struct Node *head[10];
//creating array of current pointers to track the list on each array node.
struct Node *cur[10];
void create(int v)
{
for (int i = 0; i < v; i++) {
array[i] = new Node;
head[i] = cur[i] = array[i];
array[i]->data = i;
array[i]->link = NULL;
}
}
void add(int fr, int to)
{
Node *np = new Node;
np->data = to;
np->link = NULL;
if (head[fr]->link == NULL) {
head[fr]->link = np;
cur[fr] = np;
} else {
cur[fr]->link = np;
cur[fr] = np;
}
/*Node* np1=new Node;
np1->data=fr;
np1->link=NULL;
if(head[to]->link==NULL)
{
head[to]->link=np1;
cur[to]=np1;
}else
{
cur[to]->link=np1;
cur[to]=np1;
}*/
}
void print(int a)
{
Node *p = NULL;
p = head[a];
for (; p != NULL; p = p->link)
{ cout << p->data; }
}
main()
{
int a;
cout << "enter the size of array";
cin >> a;
create(a);
//adding edges
add(1, 4);
add(1, 3);
add(0, 3);
add(0, 2);
print(0);
cout << "\n";
print(1);
//print(3);
}
解释:
1)要求用户输入一个整数(顶点数),因此我正在创建一个具有请求大小的数组。同时我将 head 和 cur 指针指向每个数组节点。数组的索引号等于顶点号。
2) 通过 add 函数将边从一个顶点添加到另一个顶点。如果边缘发出的顶点的头节点为空,则我指向 head=cur=new 节点(np),否则我在每次添加后更新 cur 指针。 Head 将指向数组索引节点。 3)打印连接到请求节点的边。
我的问题是:
1)这种实现方式对吗?
2)在上述情况下,假设我们连接顶点 1 和顶点 3。上面的代码 3 链接到 1。我想自动更新从顶点 3 到顶点 1 的连接,所以我添加了里面的代码添加函数中的注释部分。当我尝试运行它要求我输入数组大小的代码时,我输入了一些整数,它显示了分段错误。为什么?
【问题讨论】:
-
你能告诉我你输入的整数值吗?
-
我尝试将 3 和 4 作为 'a',它们都给出了分段错误。