题目描述
(线性表)设键盘输入n个英语单词,输入格式为n, w1, w2, …,wn,其中n表示随后输入英语单词个数,试编一程序,建立一个单向链表,实现:如果单词重复出现,则只在链表上保留一个。
输入
4
now come now please
输出
now come please
样例输入
3
go come keep
样例输出
go come keep
采用c++方式提交
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Lnode
{
char *a;
struct Lnode *next;
}LinkNode;
void Init(LinkNode *&L) //初始化链表
{
L=(LinkNode *)malloc(sizeof(LinkNode));
L->next=NULL;
}
int Check(LinkNode *L,char *word) //检查当前输入的单词是否已经存在
{
LinkNode *node = L->next;
while (NULL != node && strcmp(word, node->a))
{
node = node->next;
}
if (NULL != node)
{
return 1;
}
return 0;
}
void Creat(LinkNode *&L,char *word)
{
if(Check(L,word))
{
return;
}
LinkNode *p,*r=L;
p=(LinkNode *)malloc(sizeof(LinkNode));
p->a=word;
p->next=L->next; //头插法
L->next=p;
}
void Print(LinkNode *head) //因为采用头插法,所以此处采用递归输入
{
if(head==NULL)
return ;
Print(head->next);
printf("%s ",head->a);
}
int main()
{
LinkNode *head;
Init(head);
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
char *word=(char *)malloc(sizeof(char));
scanf("%s",word);
Creat(head,word);
}
Print(head->next);
return 0;
}