链表的典型应用——字典树

题目:http://acm.swust.edu.cn/oj/problem/842/

这个题目是有一点复杂的,因为在存储内容的时候又再次用了链表。

可以说它是链表题目的相当典型的例子了。

 

还是直接上代码吧。

View Code
#include "iostream"
#include "cstring"
#include "string"
#include "cstdio"
#include "algorithm"
#include "malloc.h"
using namespace std;
typedef struct word{
    char Chn[4];
    struct word *next;
}word;
typedef struct node{
    int mark;
    word *str;
    struct node *next[26];
}node;
node *head;
void InitHead(){
    head = (node *)malloc(sizeof(node));
    head->mark = 0;
    head->str = NULL;
    memset(head->next, NULL, sizeof(head->next));
}
void Build(char *Eng, char *Chn){
    node *p = head;
    word *w;
    int i, k, Len = strlen(Eng);
    for(i=0; i<Len; i++){
        k = Eng[i]-'a';
        if(p->next[k]==NULL){
            p->next[k] = (node*)malloc(sizeof(node));
            p->next[k]->mark = 0;
            p->next[k]->str = NULL;
            memset(p->next[k]->next, NULL, sizeof(p->next[k]->next));
        }
        p = p->next[k];
        if(i==Len-1){
            p->mark = 1;
            if(p->str==NULL){
                p->str=(word*)malloc(sizeof(word));
                strcpy(p->str->Chn, Chn);
                p->str->next = NULL;
            }else{
                w = p->str;
                while(w->next!=NULL) w=w->next;
                w=w->next=(word*)malloc(sizeof(word));
                strcpy(w->Chn, Chn);
                w->next = NULL;
            }
        }
    }
}
char *Find(char *Eng, int n){
    int i, j, k, Len = strlen(Eng);
    node *p = head;
    word *w;
    for(i=0; i<Len; i++){
        k = Eng[i]-'a';
        p = p->next[k];
        if(p==NULL) return "NO";
        
        if(i==Len-1){
            if(p->mark==0) return "NO";
            w = p->str;
            for(j=1; j<n && w->next!=NULL; j++) w = w->next;
            return w->Chn;
        }
    }
}
int main(){
    char Eng[100], Chn[4];
    int n;
    InitHead();
    while(cin>>Eng){
        if(strcmp(Eng, "end")==0) break;
        cin>>Chn;
        Build(Eng, Chn);
    }
    while(cin>>Eng){
        if(strcmp(Eng, "end")==0) break;
        cin>>n;
        cout<<Find(Eng, n)<<endl;
    }
    return 0;
}

但是这里有一个十分蛋疼的现象:

就是你将上面代码中的所有char *改成string之后,

竟然会出现奇怪的现象,也就是什么什么冲突。

无语呀…………………………………………………………。

转载于:https://www.cnblogs.com/o8le/archive/2012/04/26/2471968.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值