我正在使用C中的简单文本编辑器。我在链接列表中插入元素时遇到了麻烦。
这是我的结构:
struct node {
struct node *previous;
int c;
int x;
int y;
struct node *next;
}*head;
这是我的插入代码:
void checker(int ch, int xpos, int ypos)
{
int flag=0;
struct node *temp,*temp1,*insert_node=NULL;
temp=(struct node *)malloc(sizeof(struct node));
temp=head;
while(temp!=NULL)
{
if(temp->x==xpos && temp->y==ypos)
{
insert_node->c=ch;
insert_node->x=xpos;
insert_node->y=ypos;
if(temp->previous==NULL) //this is for inserting at the first
{
insert_node->next=temp;
head=insert_node;
}
else //this is for inserting in the middle.
{
temp1=temp;
temp=insert_node;
insert_node->next=temp1;
}
flag=1;
break;
}
temp=temp->next;
}
//this one's for the normal insertion and the end of the linked list.
if(flag==0)
characters(ch,xpos,ypos);
}
没有插入第一个和中间的作品。我不知道哪里出了问题。请帮帮我。
答案 0 :(得分:4)
temp=(struct node *)malloc(sizeof(struct node));
temp=head;
您正在为新节点分配空间,但随后您将丢失分配temp=head
的新节点的地址。
答案 1 :(得分:1)
问题是insert_node
是函数检查器()中的局部变量,它也被初始化为NULL。做insert_node->c
意味着NULL->c
,我相信你会同意我的观点是错误的。
尝试在使用它们之前为变量动态分配内存,你应该没问题。
答案 2 :(得分:0)
insert_node
在您发布的代码中始终为NULL。
此外,您可能希望更多地拆分代码;首先在find()
函数中隔离部分内容。