鏈表的典型應用——字典樹
題目: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之后,
竟然會出現奇怪的現象,也就是什么什么沖突。
無語呀…………………………………………………………。
posted on 2012-04-26 20:08 More study needed. 閱讀(266) 評論(0) 收藏 舉報

浙公網安備 33010602011771號