在这段代码中,我删除了链表中的元素
11->12->13->14->15->12->16
如果我想删除 12,它只会删除第一次出现的元素,即 o/p 将是
11->13->14->15->12->16
但我想删除所有出现的 12,该怎么做?
谁能给我一些意见?
#include<stdio.h>
#include<stdlib.h>
void insertbeg();
void delpos();
void display();
struct node
{
int info;
struct node *link;
}*first=NULL;
struct node *create();
int item,key;
main()
{
int choice;
while(1)
{
printf("\nchoices are:\n");
printf("\n1.Insertbeg\n 2.delpos\n 3.display\n 4.exit\n");
printf("Enter U'r choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: insertbeg(); break;
case 2: delpos(); break;
case 3: display(); break;
case 4: exit(1);
default: printf("INVALID CHOICE TRY AGAIN\n");
}
}
}
struct node *create()
{
struct node *new;
new=(struct node*)malloc(sizeof(struct node));
return(new);
}
void insertbeg()
{
struct node *new;
new=create();
printf("Enter element to be inserted: ");
scanf("%d",&item);
if(first==NULL)
{
new->info=item;
new->link=NULL;
first=new;
}
else
{
new->info=item;
new->link=first;
first=new;
}
}
void delpos()
{
int key;
struct node *temp,*prev;
if(first==NULL)
{
printf("LIST IS EMPTY\n");
return;
}
else
{
temp=first;
printf("Enter the KEY element which is to be deleted: ");
scanf("%d",&key);
/* while(temp->info!=key&&temp->link!=NULL)
{
prev=temp;
temp=temp->link;
}
if(temp->info==key)
{
prev->link=temp->link;
free(temp);
}
else
printf("key element not found in the list\n");
*/
while(temp->link != NULL)
{
if(temp->info == key)
{
prev->link = temp->link;
free(temp);
temp = prev->link;
temp = temp->link;
}
else
temp = temp->link;
}
}
}
void display()
{
struct node *temp;
temp=first;
if(temp==NULL)
{
printf("LIST IS EMPTY\n");
return;
}
else
{
printf("Elements in Linked Lists: ");
while(temp!=NULL)
{
printf("%d->",temp->info);
temp=temp->link;
}
}
}
最佳答案
我可以发现您的代码有两个问题,但它们都不会显示您的示例输入有问题。
1-
while(temp->link != NULL)
应该是
while(temp!=NULL)
2- temp = temp->link;
在
if(temp->info == key)
{
prev->link = temp->link;
free(temp);
temp = prev->link;
temp = temp->link;
}
并跳过一个元素。
关于c - 删除单向链表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5893173/