【发布时间】:2016-04-03 05:08:31
【问题描述】:
此代码用于使用邻接表创建图形。node 是垂直链表中每个元素的水平链表结构,
而graphnode 是垂直链表的结构列表。
代码编译正常,但是当第一个输入给出时,它在它之后显示分段错误。
#include<iostream>
using namespace std;
struct node //struct
{
struct node *next;
char value;
};
struct graphnode
{
struct node *start;
struct graphnode *down;
char value;
int count;
};
graphnode * creategraphnode(char val)
{
struct graphnode *newnode=new graphnode;
newnode->start=NULL;
newnode->down=NULL;
newnode->value=val;
newnode->count=0;
return newnode;
}
node *createnode(char val)
{
struct node *newnode=new node;
newnode->next=NULL;
newnode->value=val;
}
void insertgraphnode(char value,graphnode *graph)
{
struct graphnode *newnode=creategraphnode(value);
if(graph==NULL)
{
graph=newnode;
}
else
{
graphnode *temp=graph;
while(temp->down)
temp=temp->down;
temp->down=newnode;
}
}
void insertnode(graphnode *graph)
{
char val;
struct node *temp=graph->start;
cout<<"What is the outdegree of "<<graph->value;
cin>>graph->count;
cout<<"\nEnter"<<graph->count<<" nodes separated by space:";
for(int i=1;i<=graph->count;i++)
{
cin>>val;
node* newnode=createnode(val);
temp=newnode;
temp=temp->next;
}
}
void display(struct graphnode *graph)
{
if(graph==NULL)
{
cout<<"\nNo data to display";
return;
}
struct graphnode *temp=graph;
while(temp)
{
struct node *temp1=temp->start;
cout<<temp->value<<"=>> ";
if(temp1==NULL)
{
continue;
}
else
{
while(temp1)
{
cout<<temp1->value<<"-> ";
temp1=temp1->next;
}
}
cout<<"/\n";
}
}
int main()
{
struct graphnode *graph=NULL;
int totalnodes;
char val;
cout<<"\nHow many nodes does the graph contain? : ";
cin>>totalnodes;
cout<<"\nEnter "<<totalnodes<<" space separated nodes : ";
for(int i=1;i<=totalnodes;i++)
{
cin>>val;
insertgraphnode(val,graph);
}
struct graphnode *temp=graph;
while(temp->down)
{
insertnode(temp);
temp=temp->down;
}
display(graph);
return 0;
}
【问题讨论】:
-
是否有插件可以在程序崩溃时自动创建关于 SO 的问题?
-
struct node *temp=graph->start;是插入第一个节点时出现问题。那时graph就是NULL。 -
我不会调用函数 insertnode() 除非我在它之前使用过函数 insertgraphnode()
标签: c++ algorithm graph segmentation-fault g++