链表

自己用C写的,为了以后用

 1 #include "list.h"
 2    
 3    
 4 static void FreeNode(Node *node);
 5 
 6 
 7 //index为插入的序号,在该序号插入,后续内容后移,
 8 //范围从0到list->n
 9 //data为用malloc分配的数据指针
10 void AddNode(List *list,void *data,int index)
11 {
12     Node *p,*node;
13     
14     if(index<0 || index>list->n)//防止越界
15         return;
16     
17     node=(Node *)malloc(sizeof(Node));//填充data
18     node->data=data;
19 
20     p=GetNode(list,index-1);
21     node->next=p->next;
22     p->next=node;
23     if(index==list->n)    //在尾添加则更新end
24         list->end=node;
25     list->n++;
26 }
27    
28 //删除指定序号节点
29 void DeleteNode(List *list,int index)
30 {
31     Node *p,*q;
32     
33     if(index<0 || index>=list->n)
34         return;
35     
36 
37     q=GetNode(list,index-1);
38     p=q->next;
39     q->next=p->next;
40     if(p->data)
41         free(p->data);
42     free(p);
43 
44     if(index==list->n-1)    //删除尾则更新end
45         list->end=q;
46     list->n--;
47 }
48    
49    
50 //返回指定序号的节点,-1为无用头节点
51 //不成功返回NULL
52 Node *GetNode(List *list,int index)
53 {
54     int i;
55     Node *n;
56     if(index<-1 || index>=list->n)//防止越界
57         return NULL;
58     if(index==list->n-1)        //返回链表尾
59         return list->end;
60     for(i=-1,n=list->head;i<index;i++,n=n->next)
61         ;
62     return n;
63 }
64 
65 void *GetData(List *list,int index)
66 {
67     return GetNode(list,index)->data;
68 }
69 
70 //返回链表,不成功为NULL
71 List *CreateList(void)
72 {
73     List *list=(List *)malloc(sizeof(List));
74     if(list==NULL)return NULL;
75    
76     list->n=0;
77     list->head=(Node *)malloc(sizeof(Node));
78     list->head->next=NULL;    //空的头节点
79     list->head->data=NULL;
80     list->end=list->head;
81     return list;
82 }
83    
84 void DestroyList(List *list)
85 {
86     if(list->n!=0)
87         FreeNode(list->head);
88     free(list);
89 }
90    
91 //递归释放单向链表
92 static void FreeNode(Node *node)
93 {
94     if(node->next)
95         FreeNode(node->next);
96     if(node->data)
97         free(node->data);
98     free(node);
99 }
list.c
 1 #ifndef LIST_H
 2 #define LIST_H
 3 
 4 //用Create创建链表,使用完后应用Destroy删除链表释放资源
 5 //Add插入节点,需要用malloc分配的数据指针
 6 //修改或查看节点内容使用GetNode或GetData
 7 //删除节点使用Delete
 8 
 9 //为操作方便,链表包含一个空的头节点
10 //index脚标将空节点后第一个有数据的节点设为0   
11 //自己定义循环遍历链表,而不要用GetNode[i]的方式   
12 #include <stdio.h>
13 #include <stdlib.h>
14    
15 struct NodeTag
16 {
17     void *data;    //malloc分配的数据指针
18     struct NodeTag *next;
19 };
20    
21 typedef struct NodeTag Node;
22    
23 typedef struct
24 {
25     Node *head;
26     Node *end;    //链表尾,加快访问   
27     int n;  //大小
28 }List;
29    
30    
31 void AddNode(List *list,void *data,int index);
32 void DeleteNode(List *list,int index);
33 Node *GetNode(List *list,int index);
34 void *GetData(List *list,int index);
35 List *CreateList(void);
36 void DestroyList(List *list);
37 
38 
39 #endif
list.h

 

posted @ 2013-08-08 18:12  ZackCoder  阅读(150)  评论(0编辑  收藏  举报