【求助】用链表进行电话本查找删除的程序
#include <stdio.h>#include <stdlib.h>
#include <string.h>
struct link
{
char name[20];
char num[50];
struct link *next;
};
struct link *Insert(struct link *head) //插入输入的节点
{
char name2[20];
struct link *pr = head, *p = head;
p = (struct link *)malloc(sizeof(struct link));
p ->next = NULL;
scanf("nsert %s %s behind %s",p->name,p->num,name2);
int q;
q = strcmp(name2,"Nobody");
if (q == 0) head = p;
else
{
q=strcmp(pr->name,name2);
while (q!=0 && pr->next != NULL)
{
pr = pr->next;
q=strcmp(pr->name,name2);
}
if (q == 0)
{
struct link *temp = NULL;
temp = pr->next;
pr->next = p;
p->next = temp;
}
}
return head;
}
struct link *Delete(struct link *head) //删除节点
{
char name2[20];
scanf("elete %s",name2);
struct link *p = head, *pr = head;
int m;
m=strcmp(p->name,name2);
while(m != 0 && p->next != NULL);
{
pr = p;
p = p->next;
m = strcmp(p->name,name2);
}
if (m == 0)
{
if (p == head)
{
head = p->next;
}
else
{
pr->next = p->next;
}
free(p);
}
return head;
}
void Print(struct link *head) //显示电话本
{
struct link *p = head;
while (p != NULL)
{
printf("%s ",p->name);
printf("%s",p->num);
printf("\n");
p = p->next;
}
fflush(stdin);
}
void DELETE(struct link *head) //清空内存
{
struct link *p = head, *pr = NULL;
while (p != NULL)
{
pr = p;
p = p->next;
free(pr);
}
}
int main()
{
struct link *head = NULL;
char order;
scanf("%c",&order);
while(order != 'E')
{
if (order == 'I')
{
head = Insert(head);
}
else
{
if (order == 'D')
{
head = Delete(head);
}
else
{
if( order == 'P')
{
Print(head);
}
}
}
order = '\0';
scanf("%c",&order);
}
DELETE(head);
return 0;
}
用例为
Input:
Insert LiLei 14068888 behind Nobody
Insert Joker 04517999 behind LiLei
Insert Healer 987213 behind Joker
Delete LiLei
End
Output:
LiLei 14068888
Joker 04517999
Healer 987213
Joker 04517999
Healer 987213