YTU OJ 2209: 建立链表(线性表)

题目描述

(线性表)设键盘输入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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值