2009年5月7日 星期四

Linkedlist計算檔案單字 (C)

跟前篇幾乎一樣, 只是將程式改成純C的方式, 並修改執行流程, 還加上了註解...

//=================================================================
// 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 typedef struct strNode
6 {
7 struct strNode * Next; // 下一筆
8 int Count; // 統計數
9 char Text[1]; // 文字串存放(將配置足夠空間)
10 } Node;
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 && strcmp(text, node->Text)!=0) //分大小寫, 若不分改stricmp
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 printf( "\nOutput all:\n");
45 Node * node = First;
46 for( ; node!=NULL; node=node->Next)
47 printf( "%s %d\n", node->Text, node->Count);
48 }
49 //釋放所有資料空間 ---
50 void ClearAll()
51 {
52 Node * node = First;
53 Node * freeNode;
54 for( ; (freeNode=node)!=NULL; free(freeNode))
55 node=node->Next;
56 First = Last = NULL;
57 }
58 //由檔案讀取文字資料 ---
59 void ReadFromFile(char * filename, char *text)
60 {
61 FILE * file = fopen(filename, "r" );
62 if (file!=NULL)
63 {
64 while(fscanf(file, "%s", text)!=EOF)
65 Insert(text, 0);
66 fclose(file);
67 }
68 else printf("無法開啟 %s 檔案!!\n", filename);
69 }
70 // 主程式 ===
71 int main()
72 {
73 char ch='y';
74 char text[128];
75 ReadFromFile("text.txt", text); // 讀檔
76 while((ch|0x20)=='y')
77 {
78 if (First!=NULL) OutputAll(); // 顯示
79 printf( "\nInsert word:");
80 Insert( text, scanf( "%s", text)); //安插
81 printf( "\nSearch word:");
82 Search( text, scanf( "%s", text)); //搜尋
83 printf( "\nContinue? (y/n)");
84 scanf( " %c", &ch); // 繼續(y) 或離開
85 }
86 ClearAll();
87 return 0;
88 }
89 // ========== end




看來, 這次還是很不適合去賺以行計費的錢, 因為程式碼就這麼多而已~~~

沒有留言:

張貼留言