题目:多函数编程
struct word [char c[20]; struct word *next
函数1:一输入一串单词字符串,假设每个单词长度不超过19个字符,用空格隔开,把每个单词数据存在一个单向动态链表(简称单词链表)里的一个节点。
struct word create word list()/生成链表
void print word list(struct word head)//访问输出链表的元素
函数2:在单词链表中查找指定的单词,找到第一个则返回其是链表第几个节点值,否则返回0,
Int serach word (struct word *head, char *w)
函数3:在单词链表中删除指定单词, struct*del_Word( struct word *head,,char *w
函数4:主函数main()1.用动态内存分配函数申请存放N个单词空间,
输入单词“I am a good be you are a good girl”
/调用函数create word_list生成一个动态链表,分别存放了10个单词。
/调用函数 print word list/调用函数
2.输入需要查找单词
//调用函数 serach word,查找指定单词“I”,输出查找的结果
调用函数 serach word,查找指定单词“girl”,输出查找的结果
调用函数 serach word,查找指定单词“good”,输出查找的结果
3. 删除指定单词“good”,输出新链表的数据
4.删除指定单词 “I”输出新链表的数据。
5. 测试数据“ I am a good be you are a good girl
#include<string.h>
#include<stdlib.h>
#define len sizeof(struct word)
struct word
{
char c[20];
struct word*next;
};
struct word*creat_word_list()//链表的建立
{
int n=0;
struct word *head,*p1,*p2;
p1=p2=(struct word*)malloc(len);
scanf("%s",p1->c);
head=NULL;
while (p1->c!='\0')
{ n=n+1;
if (n==1) { head=p1; }
else { p2->next=p1;}
p2=p1;
if(n>9) break;//九个单词
p1=(struct word*)malloc(len);
scanf("%s",p1->c);
}
p1->next=NULL;
return head;
}
int serach_word(struct word*head,char*w)//查找元素
{
struct word*p1;
int n=1;
p1=head;
while(p1!=NULL)
{
if(strcmp(p1->c,w)==0)
{ return n;}
n++;
p1=p1->next;
}
return 0;
}
struct word*del_word(struct word*head,char*w)//节点的删除
{
struct word*p=head,*p1=head->next,*p2=head;
int n=0;//标识量
while(p1!=NULL)
{ if(n==0&&(strcmp(p->c,w)==0))//当所要查找的单词是开头单词时
{
head=p;
p=p->next;
free(head);
n=0;
p1=p->next;
p2=p;
continue;
}
if(n!=0&&strcmp(p1->c,w)==0) //当所要查找的单词不是开头单词时
{ p2->next=p1->next;
free(p1);
p1=p2->next;
}
else
{ p1=p1->next;
p2=p2->next;
}
n++;
}
return p;
}
void print_word_list(struct word*head)//链表的输出
{
struct word*p=head;
while(p!=NULL)
{
printf("%s ",p->c);
p=p->next;
}
printf("\n");
}
int main()
{
struct word*head,*p;
char *del,*ser;
del=(char*)malloc(20*sizeof(char));
ser=(char*)malloc(20*sizeof(char));
head=creat_word_list();//建立链表
print_word_list(head);//输出链表
printf("输入要查找的单词:");
scanf("%s",ser);
printf("%d\n",serach_word(head,ser));//输出所在位置,重复三次
printf("输入要查找的单词:");
scanf("%s",ser);
printf("%d\n",serach_word(head,ser));
printf("输入要查找的单词:");
scanf("%s",ser);
printf("%d\n",serach_word(head,ser));
printf("输入要删除的单词:");
scanf("%s",del);
print_word_list(del_word(head,del));//调用删除节点的函数,并输出
printf("输入要删除的单词:");
scanf("%s",del);
print_word_list(del_word(head,del));//调用删除节点的函数,并输出
return 0;
}