c - C中双链表中的意外错误

标签 c data-structures linked-list

我正在尝试根据节点数 n 在我的双向链表中插入元素。就像如果 n4 那么输入的元素数量是:34 ​​45 32 1 但是得到 segmentation fault。谁能告诉我哪里出错了?

#include<stdio.h>
#include<malloc.h>

struct node{
            struct node *prev;
            struct node *next;
            int info;
            }*start;

create_list(int num)
{
 printf("Hi I entered!\n");
 struct node *q,*tmp;
 tmp= malloc(sizeof(struct node));
 tmp->info=num;
 tmp->next=NULL;

 if(start==NULL)
 {
  printf("Hi I am null!\n");
  tmp->prev=NULL;
  start->prev=tmp;
  start=tmp;
 }

 else
 {
  printf("Hi I am no more null!\n");
  q=start;
  while(q->next!=NULL)
  q=q->next;
  q->next=tmp;
  tmp->prev=q;
  }
}




int main(){

int choice, n, elem,i;
start = NULL;

 printf("Enter your choice of number: \n");
 scanf("%d", &choice);

 while(1)
      {

switch(choice)
{
  case 1:
     printf("Enter the number of nodes: \n");
     scanf("%d", &n);

     for(i=0; i<n; i++)
     {
       printf("Enter the elemnts: \n");
       scanf("%d", &elem);
       create_list(elem);
     }
     break;

 default:
         printf("You have tyoed wrong!\n");
     }

   }
 }

最佳答案

if(start==NULL)
{
  ...
  start->prev=tmp;

如果start为NULL,则上面的赋值不正确。

我建议在分配新节点时将 prev 初始化为 NULL:

tmp= malloc(sizeof(struct node));
tmp->info=num;
tmp->next=NULL;
tmp->prev=NULL;        // add this

if(start==NULL)
{
    printf("Hi I am null!\n");
    start=tmp;
}
....

关于c - C中双链表中的意外错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18763139/

相关文章:

c - 如何将文件的内容存储到数组中(C)

c - 不可靠的信号 API - 代码未按预期工作

c - 追加到数组末尾

java - 我们可以不在 Trie 构造函数中初始化引用数组吗

c - 如何根据字符串删除链表中的节点

c++ - RGB 到 LAB 并返回错误

data-structures - n 个元素的堆的高度

c - 这段代码有什么问题?

c++ - 查找链表的 "Nth node from the end"

c++ - 我不断在链接列表上收到段错误