2016-12-15 67 views
1

我已经写了这段代码,按位置插入到链表中。为什么插入函数总是附加在链表的末尾?

void insert(node *list, int data, int position) { 
    int c; 

    node *temp; 
    node *prev; 
    node *curr; 

    curr = list; 

    temp = malloc(sizeof(node)); 
    temp->num = data; 

    if (curr == NULL) { 
     curr = temp; 
     curr->next = NULL; 
    } else { 
     while (curr != NULL && c != position) { 
      prev = curr; 
      curr = curr->next; 
      c++; 
     } 
     if (c = 0) { 
      temp->next = curr; 
      curr = temp; 
     } else if (curr == NULL) { 
      prev->next = temp; 
     } else { 
      prev->next = temp; 
      temp->next = curr; 
     } 
    } 
} 

但是,我相信这个块总是执行,不管是什么,数据都会被附加到链表的末尾。

else if (curr == NULL) { 
     prev->next = temp; 

为什么curr总是空?如果位置小于列表中元素的数量,它不应该为空......

+2

首先:'int c = 0;' – LPs

回答

0

您尚未将c变量初始化为0。也条件 如果(C = 0)应该已经如果(C == 0)

TEMP->下一= NULL也应TEMP-> NUM =数据之后进行否则它将保持未初始化如果是

 else if (curr==NULL) { 
       prev->next=temp; 
     } 

这些都是我注意到的。

0

有你的代码中的多个问题:

  • 局部变量c未初始化。在没有事先初始化的情况下使用它会调用未定义的行你应该把它定义是这样的:

    int c = 0; 
    
  • 测试if (c = 0)c0价值和总是失败。使用==操盘手:

    if (c == 0) { 
        ... 
    
  • 您必须返回list并设置listcurr是元件插入在列表的开始(位置0),或者如果该列表是空的。

这里是一个改进版本:

node *insert(node *list, int data, int position) { 
    node *temp = malloc(sizeof(node)); 
    if (temp == NULL) { 
     return NULL; 
    } 
    temp->num = data; 
    if (list == NULL || position <= 0) { 
     temp->next = list; 
     return temp; 
    } else { 
     node *curr = list; 
     while (position-- > 0 && curr->next != NULL) { 
      curr = curr->next; 
     } 
     temp->next = curr->next; 
     curr->next = curr; 
     return list; 
    } 
} 
+1

'void insert' --->'node * insert';) – LPs

+0

如何从void函数返回节点*或NULL? – user3283146

+1

@LP答案已更正。谢谢。 – chqrlie

0

你必须有一个局部变量:c

该变量具有自动存储并且其起始值不确定。 您必须初始化它

int c = 0; 

否则其初始值可以在任何时刻功能寄存器旧值或内存垃圾被调用,所以

while (curr!=NULL && c != position) 

行为是不确定的。


而且,如果一段时间后,检查窃听:平等关系运算符是==

if (c=0) 

必须

if (c==0) 

否则,你要分配0c,而不是测试其值。