在C双键链表意外错误 [英] Unexpected error in double linked list in C

查看:143
本文介绍了在C双键链表意外错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图插入基于节点的数目在我的双向链表元素 N 。就像如果 N 4 然后进入元素的个数是: 34 45 32 1 但得到分段故障。谁能告诉我在哪里,我错了?

 #包括LT&;&stdio.h中GT;
#包括LT&;&malloc.h所GT;结构节点{
            结构节点* preV;
            结构节点*接下来的;
            诠释信息;
            }*开始;create_list(INT NUM)
{
 的printf(我进入\\ n!);
 结构节点* Q,* tmp目录;
 TMP =的malloc(sizeof的(结构节点));
 tmp->信息= NUM​​;
 tmp->接着= NULL; 如果(开始== NULL)
 {
  的printf(我是空\\ n!);
  tmp-> preV = NULL;
  开始 - > preV = TMP;
  开始= tmp目录;
 } 其他
 {
  的printf(我没有更多的空\\ n!);
  Q =启动;
  而(Q-GT&;!下次= NULL)
  Q = Q->接着,
  Q->接下来= TMP;
  tmp-> preV = Q;
  }
}
诠释主(){INT选择,N,ELEM,我;
开始= NULL; 的printf(请输入您的号码选择:\\ n);
 scanf函数(%d个,&安培;选择); 而(1)
      {开关(选择)
{
  情况1:
     的printf(输入节点的数量:\\ n);
     scanf函数(%d个,&安培; N);     对于(i = 0; I< N;我++)
     {
       的printf(请输入elemnts:\\ n);
       scanf函数(%d个,&安培; ELEM);
       create_list(ELEM);
     }
     打破; 默认:
         的printf(你错了tyoed \\ n!);
     }   }
 }


解决方案

 如果(开始== NULL)
{
  ...
  开始 - > preV = TMP;

如果启动为NULL,上面则分配不正确。

我会建议初始化 $ P $光伏为NULL,当​​你分配新的节点是这样的:

  TMP =的malloc(sizeof的(结构节点));
tmp->信息= NUM​​;
tmp->接着= NULL;
tmp-> preV = NULL; //添加此如果(开始== NULL)
{
    的printf(我是空\\ n!);
    开始= tmp目录;
}
....

I am trying to insert elements in my double linked list based on the number of nodes n. Like if n is 4 then number of elements entered are: 34 45 32 1 but getting segmentation fault. Can anybody tell me where I am going wrong?

#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;

If start is NULL, then the assignment above is incorrect.

I would suggest initializing prev to NULL when you allocate the new node like this:

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双键链表意外错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆