简单链表的应用


链表可以解决很多实际问题,比如数据结构课程上讲的多项式运算、求解约瑟夫问题操作系统原理中的内存管理器实现等等。举一个在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。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM