首先,我是图形学的新手。经过图形的概念研究。我想在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),要求用户输入一个整数(节数顶点),因此我创建与请求的大小的阵列。同时,我将指针指向每个数组节点的指针和cur指针。数组的索引号等于顶点数。
2)通过添加函数从一个顶点向另一个顶点添加边。如果边缘发出的顶点的头节点为空,那么我指向头= cur =新节点(np),否则我在每次加法后更新cur指针。 Head将指向数组索引节点。 3)打印连接到请求节点的边缘。
我的问题是:
1)是实施正确的这种方式?
2)在上面的例子中,让我们假设我们连接顶点1和顶点3.与上面的代码3连接到1.我想自动更新从顶点3到顶点1的连接,所以我添加了代码里面的注释部分添加function.When我试着运行代码它要求我输入数组的大小,我输入一些整数它显示我的分段错误。为什么?
你能告诉我你输入的整数值是多少? – cryptomanic
我试着给3和4作为'a',他们都给分段错误。 – Dhineshkumar