2013-08-05 70 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的地址。