problem description] create a linked list, each node including: name, age. Enter an age, and delete the node if the node in the linked list contains an age equal to that age.
[input form] the number of data to be entered first, and then the information of each node; after the input is completed, enter the age information of the node to be deleted.
[output form] if the data to be deleted is found in the linked list, the node is deleted and the deleted linked list is displayed, and if no data is found, the output "no data".
[sample input]
4
mu 20
yu 21
qu 19
ku 20
20
[sample output]
yu 21
qu 19
[sample input]
4
mu 20
yu 21
qu 19
ku 20
9
[sample output]
no data
my code
< H1 > include < stdio.h > < / H1 > < H1 > include < stdlib.h > < / H1 > int flag = 0;
struct stu {
char name[12];
int age;
struct stu *next;
};
struct stu * creat (int n)
{
struct stu*head = NULL;
struct stu *p1, *p2;
p1 = p2 = new stu;
scanf("%s %d", p1->name, &p1->age);
for (int i = 1; i < n; iPP)
{
if (i == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = new stu;
scanf("%s %d", p1->name, &p1->age);
}
p2->next = p1;
p2 = p1;
p2->next = NULL;
return head;
}
struct stu select (struct stu head, int n point int m)
{
struct stu *p1 = head,*p2=p1,*temp=p1;
for (int i = 0;; iPP) {
if (head->age == m) {
free(head);
head = p1->next;
p1 = head;
p2 = head;
flag = 1;
}
else if (p1->next != NULL) {
p2 = p1;
p1 = p1->next;
if (p1->age == m) {
p2->next = p1->next;
temp = p1;
p1 = p1->next;
free(temp);
flag = 1;
}
}
else if(p1->next==NULL&&p1->age==m) {
p2->next = NULL;
free(p1);
p1 = p2;
flag = 1;
}
if (p1->next == NULL && p1->age != m)
break;
}
return head;
}
int main ()
{
struct stu*head,*p;
int m, n;
scanf("%d", &n);
head=creat(n);
scanf("%d", &m);
select(head, n, m);
if (flag == 0) {
printf("no data");
}
else {
p = head;
do {
printf("%s %d", p->name, p->age);
p = p->next;
} while (p != NULL);
}
system("pause");
return 0;
}
Please help me to see what went wrong. In the case of NO DATA, you can output other cases, but the compiler cannot prompt P1 conflict. Thank you!