-1
此代碼用於使用鄰接列表創建圖。 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當ap節目壓碎? – Slava
'struct node * temp = graph-> start;'是第一個節點插入時的問題。那時'graph'是'NULL'。 –
我不會調用函數insertnode(),除非我在它之前使用了函數insertgraphnode() –