鏈表可以解決很多實際問題,比如數據結構課程上講的多項式運算、求解約瑟夫問題,操作系統原理中的內存管理器實現等等。舉一個在Windows通過鏈表搜索文件的實例,代碼如下(vc6.0中編譯通過)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
#include <stdio.h>
#include <windows.h>
struct
DirList{
char
table[256];
DirList *pNext;
};
DirList *first,*newlist,*last;
//加入文件夾鏈表
void
AddList(
char
*list)
{
newlist=
new
DirList;
strcpy
(newlist->table,list);
newlist->pNext=NULL;
//假如文件鏈表為空,那么第一個和最后一個節點都指向新節點
if
(first==NULL)
{
first=newlist;
last=newlist;
}
//不為空,則原來最后一個節點指向新節點
else
{
last->pNext=newlist;
last=newlist;
}
}
//查找文件,並把找到的文件夾加入文件夾鏈表
void
FindFile(
char
*pRoad,
char
*pFile)
{
char
FileRoad[256]={0};
char
DirRoad[256]={0};
char
FindedFile[256]={0};
char
FindedDir[256]={0};
strcpy
(FileRoad,pRoad);
strcpy
(DirRoad,pRoad);
strcat
(DirRoad,
"\\*.*"
);
WIN32_FIND_DATA findData;
HANDLE
hFindFile;
hFindFile=FindFirstFile(DirRoad,&findData);
if
(hFindFile!=INVALID_HANDLE_VALUE)
{
do
{
if
(findData.cFileName[0]==
'.'
)
continue
;
//假如是文件夾,則假如文件夾列表
if
(findData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
{
strcpy
(FindedDir,pRoad);
strcat
(FindedDir,
"\\"
);
strcat
(FindedDir,findData.cFileName);
//加入文件夾列表
AddList(FindedDir);
memset
(FindedDir,0x00,256);
}
//繼續查找
}
while
(FindNextFile(hFindFile,&findData));
}
strcat
(FileRoad,
"\\"
);
strcat
(FileRoad,pFile);
//查找要查找的文件
hFindFile=FindFirstFile(FileRoad,&findData);
if
(hFindFile!=INVALID_HANDLE_VALUE)
{
do
{
strcpy
(FindedFile,pRoad);
strcat
(FindedFile,
"\\"
);
strcat
(FindedFile,findData.cFileName);
//輸出查找到的文件
printf
(
"%s\n"
,FindedFile);
memset
(FindedFile,0x00,256);
}
while
(FindNextFile(hFindFile,&findData));
}
}
int
SeachFile(
char
*Directory,
char
*SeachFile)
{
DirList NewList;
strcpy
(NewList.table,Directory);
NewList.pNext=NULL;
last=&NewList;
first=&NewList;
while
(
true
)
{
DirList *Find;
//假如鏈表不為空,提取鏈表中的第一個節點,並把第一個節點指向原來第二個
if
(first!=NULL)
{
//提取節點
Find=first;
//並把第一個節點指向原來第二個
first=first->pNext;
//在提取的節點的目錄下查找文件
FindFile(Find->table,SeachFile);
}
//為空則停止查找
else
{
printf
(
"文件搜索完畢\n"
);
return
0;
}
}
return
0;
}
int
main(
int
argc,
char
* argv[])
{
if
(argc!=3) {
printf
(
"程序名 文件目錄 要搜索的文件名\n"
);
return
0;
}
SeachFile(argv[1],argv[2]);
return
0;
}
|
執行效果如下,測試搜索c:\windows目錄中的記事本程序notepad.exe。