2009年5月7日 星期四

Linkedlist計算檔案單字

//=================================================================
// 20090506 知識 +
// http://tw.knowledge.yahoo.com/question/question?qid=1509050609490
// 發問者 : http://tw.knowledge.yahoo.com/my/my?show=AD05086376
//=================================================================

先依發問者的需求建立一個文字檔 Text.txt, 內容為...
I'm so eager to see you again
but i wouldn't ask to see you

接著就是程式碼囉....


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 struct Node
6 {
7 struct Node * Next;
8 int Count;
9 char Text[1];
10 };
11
12 Node * First = NULL;
13 Node * Last = NULL;
14
15 Node * Search(char *text, int disp)
16 {
17 Node * node = First;
18 while( node!=NULL && stricmp(text, node->Text)!=0) // 不分大小寫, 要分改用strcmp
19 node = node->Next;
20 if (disp) printf("'%s' is%sfound!\n", text, (node==NULL)? " not ": " " );
21 return node;
22 }
23
24 Node * Insert(char *text, int disp)
25 {
26 Node * node = Search(text, disp);
27 if (node==NULL)
28 {
29 node = (Node *) malloc(sizeof(Node)+strlen(text)+1);
30 strcpy(node->Text, text);
31 node->Count = 1;
32 node->Next = NULL;
33 if (First==NULL) First=node;
34 if (Last!=NULL) Last->Next = node;
35 Last = node;
36 if (disp) printf("'%s' is insertend to the list.\n", text);
37 }
38 else node->Count++;
39 return node;
40 }
41
42 void OutputAll()
43 {
44 for( Node * node = First; node!=NULL; node=node->Next)
45 printf( "%s %d\n", node->Text, node->Count);
46 }
47
48 void ClearAll()
49 {
50 Node * freeNode;
51 for( Node * node = First; (freeNode=node)!=NULL; free(freeNode))
52 node=node->Next;
53 First = Last = NULL;
54 }
55
56 int ReadFromFile(char * filename, char *text)
57 {
58 FILE * file = fopen(filename, "r" );
59 if (file!=NULL)
60 {
61 while(fscanf(file, "%s", text)!=EOF)
62 Insert(text, 0);
63 fclose(file);
64 }
65 else printf無法開啟 %s 檔案!!\n", filename);
66 return (file==NULL);
67 }
68
69 int main()
70 {
71 char text[100];
72 if (ReadFromFile("Text.txt", text))
73 return 1;
74 printf( "Output all:\n");
75 OutputAll();
76 while(1)
77 { // Insert 與 Search 迴圈, 若輸入字首不是 a~z與A~Z 則跳離
78 printf( "\nInsert word:");
79 if (scanf( "%s", text)!=1 || (text[0]|0x20)%'a'>=26) break;
80 Insert( text, 1);
81 printf( "\nSearch word:");
82 if (scanf( "%s", text)!=1 || (text[0]|0x20)%'a'>=26) break;
83 Search( text, 1);
84 }
85 ClearAll();
86 return 0;
87 }



看來, 我很不適合去賺以行計費的錢, 因為我會很吃虧呀~~~

沒有留言:

張貼留言