【发布时间】:2018-01-23 09:53:24
【问题描述】:
我试图在 C 中创建一个链表,但我遇到了分段错误? 我刚刚定义了结构,然后创建了一个简单的函数来创建单个节点并为其分配值,然后一个名为 append 的函数在列表末尾添加一个节点,主程序接受输入并追加列表,最后它打印列表。
#include <stdio.h>
#include <stdlib.h>
typedef struct list {
int value ;
struct list *next ;
}node;
node* create(int value, node *next)
{
//creating node and allocating memory
node* new_node = (node*)malloc(sizeof(node));
//assigning values to the node
new_node->value = value ;
new_node->next = next ;
return new_node;
}
node* append(int value,node *head){
//creating the node
node* new_node = create(value,NULL);
//handling the case in which the head is NULL, other words when we don't have a previous node to append to
if (head == NULL) {
head = new_node;
return head;
}
//the standard procesdure
else{
//traversing the list
node* cursor = head ;
while (cursor != NULL) {
cursor = cursor->next ;
}
// appending the node to the list
cursor->next = new_node;
return head;
}
}
int main(int argc, char const *argv[]) {
int n ;
printf("Enter the length of the list you wish to make\n");
scanf("%d",&n );
node* head = NULL;
while (n--) {
int value;
printf("enter the value of the %d node\n",n);
scanf("%d",&value);
head = append(value,head);
}
//printing the list
node* cursor = head ;
while (cursor !=NULL) {
printf("%d\n",cursor->value );
cursor = cursor->next;
}
return 0;
}
【问题讨论】:
标签: c segmentation-fault