2015-02-10 38 views
0

这里是我用C编写链接列表的代码。它在while循环执行一次后给出运行时错误。 Plz帮助我纠正我的代码。 (完全搞不清楚错误在哪里)。我首先创建一个头节点,然后向它添加子节点。通过头部和节点制作链接列表

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node nd; 
typedef nd *link; 

struct node{ 
    int data; 
    link next; 
}; 

typedef struct { 
    int size; 
    link head; 
}list; 

void create(link temp) 
{ 
    link new; 
    new=(link)malloc(sizeof(nd)); 
    printf("enter data: "); 
    scanf("%d",new->data); 
    temp->next=new; 
    temp=temp->next; 
} 

list createlist() 
{ 
    list sl; 
    sl.size=0; 
    sl.head=0; 
    return sl; 
} 

int main() 
{ 
    list sl; 
    sl=createlist(); 
    link temp; 
    temp=sl.head; 
    char c; 
    while (1) 
    { 
     printf("Add node?: "); 
     scanf(" %c",&c); 
     if (c=='y') 
      { 
      create(temp); 
      sl.size++; 
      } 
     else 
      break; 
    } 
    return 0; 
} 
+0

它在哪一行崩溃?你给了什么输入? – 2015-02-10 03:19:57

+1

将create()中的变量'new'更改为其他值将会很好。这不是你的问题,只是不好的风格。 – KeithSmith 2015-02-10 03:20:28

+0

不应该scanf(“%d”,new-> data);是scanf(“%d”,&new-> data); – KeithSmith 2015-02-10 03:28:31

回答

2

createlist()函数返回到本地变量超出范围则返回在经过了参考。您应该返回一个基于堆的值:

list* createlist() { 
    list* sl = (list*)malloc(sizeof(list)); 
    sl->size=0; 
    sl->head=0; 
    return sl; 
    } 
0

最初temp指向NULL。 temp = sl.head;

在create(temp)temp-> next = new;

您正在取消引用NULL,地址0x0。当我这样做时,我会遇到分段错误。

需要更改算法。 调试器立即显示此问题。

0

您可以使用指向temp的指针。如果你没有使用指向节点的typedef,读起来会更容易。我没有测试过这个,但它应该是关闭的:

nd ** create(nd **temp) 
{ 
    nd *new; 
    new=(nd *)malloc(sizeof(nd)); /* this cast shouldn't be needed */ 
    printf("enter data: "); 
    scanf("%d",&(new->data)); 
    new->next = NULL; 
    *temp = new; 
    return &(new->next); 
} 
/* ... */ 

int main() 
{ 
nd **temp; 
temp = &(sl.head); 
/* ... */ 
     temp = create(temp); 
/* ... */ 
}