我写这段代码是为了删除链接列表中的任何项目,
this is the output after insertion
16 --> 15 --> 14 --> 13 --> 12 --> 11 -->
when i delete 11 the output is like this
16 --> 15 --> 14 --> 13 --> 12 --> 0 -->
最后如何去掉零?
typedef struct node
{
int data;
struct node *next;
}node;
node *getnode()
{
node *x;
x = (node*)malloc(sizeof(node));
if (x==NULL)
{
printf("no memory \n");
exit(1);
}
return x;
}
node *insert_front(int item , node *first)
{
node *temp;
temp = first;
temp = getnode();
temp -> data = item;
temp -> next = first;
return temp;
}
void *display(node *first)
{
node *temp;
temp = first;
if (temp == NULL)
{
printf("list is empty \n");
return ;
}
while (temp != NULL)
{
printf(" %d --> ",temp -> data);
temp = temp -> next;
}
}
void delete_middle(int item, node *first)
{
node *temp;
node *store_addr;
int value;
temp = first;
if (temp == NULL)
{
printf("list is empty \n");
return ;
}
while(temp!=NULL)
{
if (temp->data == item)
{
if(temp->next != NULL)
{
temp->data = temp->next->data;
temp->next = temp->next->next;
}
else
free(temp);
break;
}
temp = temp->next;
}
}
main()
{
node *first;
int item = 11,ch,i;
first = NULL;
while(1)
{
printf("\n 1.insert front \n 2.display \n 3. delete middle \n 4.quit\n");
scanf ("%d",&ch);
switch(ch)
{
case 1: // printf("\nenter the item to be inserted \n");
//scanf("%d",&item);
for(i=0 ;i<6;i++)
first = insert_front (item++ , first);
break;
case 2: display(first);
break;
case 3 : printf("delete in middle \n");
scanf("%d",&item);
delete_middle(item, first);
break;
case 4: exit(0);
break;
}
}
}
最佳答案
在你的代码里试试这个,
while(temp!=NULL)
{
if (temp->data == item)
{
if(temp->next != NULL)
{
prev->next = temp->next;
}
free(temp);
break;
}
prev = temp;
temp = temp->next;
}