2013-08-05 71 views
0

我正在使用C语言编写一个简单的文本编辑器。我在插入元素时遇到了麻烦。插入链接列表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

你的结构在哪里? – someone

+0

opps对不起,我忘记了,我会更新它。 – buzzcarla

+0

在您的代码插入第一..insert_node->左侧应为空,因为它是现在的第一个节点 –

回答

0

insert_node在您发布的代码中将始终为NULL。

此外,你可能想要更多地分割你的代码;首先在find()函数中隔离它的一部分。

1

问题是insert_node是函数checker()中的一个局部变量,它也初始化为NULL。做insert_node->c意味着NULL->c,我相信你会同意我的看法是错误的。

尝试在使用它们之前为您的变量动态分配内存,你应该没问题。

4
temp=(struct node *)malloc(sizeof(struct node)); 
temp=head; 

你为一个新节点分配空间,但你失去这个新节点分配temp=head的地址。