C语言-数据结构-删除句子中重复的单词
发布网友
发布时间:2022-04-24 17:19
我来回答
共1个回答
热心网友
时间:2023-05-15 03:01
#include <stdio.h>
#include <malloc.h>
#define WORDSIZE 20
typedef struct Node
{
char ch[WORDSIZE];
struct Node *next;
}WordNode;WordNode *NodeCreate(char *str)
{
WordNode *head=NULL, *p=NULL, *q=NULL;
int i=0;
q=head=(WordNode*)malloc(sizeof(WordNode));
while(*str!='\0')
{
p = (WordNode*)malloc(sizeof(WordNode));
if(p)
{
while(*str!=' ' && *str!= '\0')
p->ch[i++] = *str++;
p->ch[i]='\0';
q->next = p;
p->next=NULL;
q=p;
i=0;
if(*str)
str++;
}
}
return head;
}
void Find(WordNode *head, char *str)
{
WordNode *p=head->next;
int i, flag;
while(p)
{
for(i=0,flag=0;str[i]==p->ch[i]; i++)
if(str[i]=='\0')
flag = 1;
if(flag)
break;
p=p->next;
}
if (flag)
printf("存在!\n");
else
printf("不存在!\n");
}int cmp(char *p1, char *p2)
{
int i;
for(i=0;p1[i]==p2[i]; i++)
if(p1[i]=='\0')
return 0;
return *p1-*p2;
}
void RemoveDuplicates(WordNode *head)
{
WordNode *p = head->next;
char *temp;
while (p != NULL)
{
temp = p->ch;
WordNode *pBefore = p;
WordNode *deleteMe = p->next;
while (pBefore->next != NULL)
{
if (cmp(deleteMe->ch,temp)==0)
{
pBefore->next = deleteMe->next;
free(deleteMe);
deleteMe = pBefore->next;
}
else
{
pBefore = pBefore->next;
deleteMe = pBefore->next;
}
}
p = p->next;
}
}void Sort(WordNode *head)
{
WordNode *p,*q,*r,*s;
r=(WordNode*)malloc(sizeof(WordNode));
r=head;
for(s=head->next;s->next;s=s->next)
{
p=s; q=p->next;
while(q)
{
if(cmp(p->ch,q->ch)>0)
{
if(p==head->next)
{
p->next=q->next;
q->next=p;
head->next=q;
q=p->next;
}
else
{
r->next=q;
p->next=q->next;
q->next=p;
r=q;q=p->next;
}
}
else
{
r=r->next;
p=p->next;
q=q->next;
}
}
r=s;
}
} void Print(WordNode *head)
{
WordNode *p=head->next;
while(p)
{
printf("%s ",p->ch);
p = p->next;
}
printf("\n");
}
int main(void)
{
char str[100];
WordNode *head=NULL;
gets(str);
head = NodeCreate(str);
printf("产生的单词列表:\n");
Print(head);
printf("请输入要查找的单词:");
scanf("%s",str);
Find(head, str);
RemoveDuplicates(head);
printf("删除重复的单词后:\n");
Print(head);
Sort(head);
printf("排序后的单词:\n");
Print(head);
return 0;
}
运行后: