在这里,我的代码显示了函数中的分段错误,该函数delete_node
从双向链表中删除了具有给定编号的节点。如果我删除第一个元素或最后一个元素,则会显示分段错误。如果我尝试删除其间的元素,它只需将其值替换为“0”。另外请说明为什么printlist
当我取消注释时函数中的注释命令显示分段错误。
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
struct node *first=NULL;
struct node *insertatbeg(struct node* list,int number)
{
struct node *new_node=malloc(sizeof(struct node));
new_node->data=number;
new_node->next=list;
new_node->prev=NULL;
return new_node;
}
struct node *insertatend(struct node* list,int number)
{
struct node* new_node;
struct node *curr=list;
new_node=malloc(sizeof(struct node));
new_node->data=number;
if(list==NULL)
{
new_node->next=list;
new_node->prev=NULL;
return new_node ;
}
else
{
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=new_node;
new_node->next=NULL;
new_node->prev=curr;
return list;
}
}
///Till here no error for sure
////////////////////////////////////////////////////////
void printlist(struct node *list)
{
int i=0;
struct node *p;
for(p=list;p!=NULL;p=p->next)
{
//printf("\nCurr=%d Prev=%d Next=%d\n",p->data,(p->prev)->data,(p->next)->data);//uncomment this & Error(Segmentation Fault comes)
printf("%d->",p->data);
++i;
}
printf("NULL\n");
printf("size=%d\n",i);
}
////////////////////////////////////////////
struct node *delete_node(struct node *list, int number)
{
struct node *curr,*previous;
for(curr=list,previous=NULL;curr!=NULL && curr->data!=number; previous=curr,curr=curr->next, (curr->next)->prev=previous)
;
if(curr==NULL)
{
printf("Sorry..Could not find the element..!!!\n");
return list;
}
if(curr->prev==NULL)
{
(curr->next)->prev=NULL;
free(curr);
return list;
}
if(curr->next==NULL)
{
(curr->prev)->next=NULL;
free(curr);
return list;
}
else
{
(curr->prev)->next=curr->next;
(curr->next)->prev=curr->prev;
free(curr);
return list;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
}
int main()
{
first=insertatbeg(first,3);
first=insertatend(first,2);
first=insertatbeg(first,1);
//Till here output is fine and is 1->3->2
printlist(first);
//first=delete_node(first,1);
//first=delete_node(first,2);
first=delete_node(first,3);
printlist(first);
return 0;
}