此代码用于使用adjacency-list创建图形。
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;
}
是垂直链表的结构。
代码正在正确编译,但是当给出第一个输入时,它会在它之后显示分段错误。
def move_chars(s, index):
to_index = s.find('__') # index of destination underscores
chars = list(s) # make mutable list
to_move = chars[index:index+2] # grab chars to move
chars[index:index+2] = '__' # replace with underscores
chars[to_index:to_index+2] = to_move # replace underscores with chars
return ''.join(chars) # stitch it all back together
print(move_chars('ABAB__AB', 0))
print(move_chars('__ABABAB', 3))
答案 0 :(得分:0)
如果我没错,你的代码至少有三个问题。
1)您的createnode()
不会返回创建的节点;添加return newnode;
2)你的insertgraphnode()
没有改变调用函数中的第二个参数;所以,当你在main()
insertgraphnode(VAL,曲线图);
graph
是NULL
;在insertgraphnode()
内你更改了值,但在函数graph
之外仍然是NULL
;永远。这会导致分段错误。
您可以解决此更改insertgraphnode()
,因此第二个参数是指向指针并传递&graph
。
另一种解决方案是修改insertgraphnode()
以返回graph
值
graphnode * 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;
}
return graph;
}
以这种方式调用它
graph = insertgraphnode(val,graph);
3)while
中的display()
进入循环,因为您不会更改temp