2.链表之双链表
head.h
1 #ifndef __HEAD_H__
2 #define __HEAD_H__
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <error.h>
8 #include <errno.h>
9
10 #define error_exit(_errmsg_) error(EXIT_FAILURE, errno, _errmsg_)
11
12 typedef struct node
13 {
14 struct node *pre;
15 char filename[64];
16 struct node *next;
17 }LinkNode;//定义链表节点数据类型
18
19 typedef struct list
20 {
21 LinkNode *head;
22 int tlen;
23 int clen;
24 }DouList;//定义表头(不是存数据的那个头节点)
25
26 DouList *CreateDouList(int len);
27 int InsertDouList(DouList *list, char *filename);
28
29 #endif
doulist.c
1 #include "head.h"
2
3 DouList *CreateDouList(int len)
4 {
5 DouList *list = malloc(sizeof(DouList));//定义表头地址,申请该地址
6 if(NULL == list) {
7 error_exit("fail to malloc");
8 }
9
10 list->tlen = len;//初始化
11 list->clen = 0;
12 list->head = malloc(sizeof(LinkNode));//申请头节点/始终不存数据
13 if(NULL == list->head) {
14 error_exit("fail to malloc");
15 }
16 list->head->pre = list->head->next = NULL;//初始化前趋/后继
17 return list;//返回表头地址
18 }
19
20 int InsertDouList(DouList *list, char *filename)
21 {
22 LinkNode *temp = malloc(sizeof(LinkNode));
23 if(NULL == temp) {
24 error_exit("fail to malloc");
25 }
26 strcpy(temp->filename,filename);
27
28 temp->next = list->head->next;
29 temp->pre = list->head;
30 list->head->next = temp;
31 if (temp->next != NULL)
32 temp->next->pre = temp;
33 list->clen++;
34
35 return 0;
36 }
37
38 int ShowDouList(DouList *list)
39 {
40 LinkNode *p = NULL;
41 p = list->head->next;
42
43 while (p != NULL)
44 {
45 printf("%s ", p->filename);
46 p = p->next;
47 }
48 printf("\n");
49 return 0;
50 }
main.c
1 #include "head.h"
2
3 int main(void)
4 {
5 DouList *doulist = NULL;
6 char buff[64] = {0};
7 int i = 0;
8
9 doulist = CreateDouList(10);
10 for (i = 0;i < 10;i++)
11 {
12 sprintf(buff, "filename_%d", i);
13 InsertDouList(doulist, buff);
14 }
15 ShowDouList(doulist);
16
17 return 0;
18 }
makefile
1 doulist:doulist.c main.c 2 gcc $^ -o $@ 3 .PHONY: 4 clean: 5 rm doulist
浙公网安备 33010602011771号