链表的C语言实现

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <assert.h>
 4 /*
 5 * 建立节点结构
 6 */
 7 typedef struct node{
 8     int data;
 9     struct node *pNext;
10 }*pNODE,NODE;
11 /*
12 * 建立头节点.
13 */
14 pNODE Create()
15 {
16     pNODE p;
17     p=(pNODE)malloc(sizeof(NODE));
18     assert(p);
19     p->pNext=NULL;
20     return p;
21 }
22 /*
23 * 遍历所有节点
24 */
25 void Visit(const pNODE head){
26     pNODE p=head->pNext;
27     while(p){
28         printf("%d\t",p->data);
29         p=p->pNext;
30     }
31 }
32 /*
33 * 删除指定的值.
34 */
35 void DeleteValue(const pNODE head,int data)
36 {
37     pNODE p=head,temp;
38     while(p->pNext){
39         if(p->pNext->data==data){
40             temp=p->pNext;
41             p->pNext=temp->pNext;
42             free(temp);     
43         }
44         p=p->pNext;
45     }
46 }
47 /*
48 * 删除指定的位置的节点.索引从1开始.
49 * 超出索引则不删除.
50 */
51 void Delete(const pNODE head,unsigned int i)
52 {
53     pNODE p=head,temp;
54     while(i>1&&--i&&p->pNext)
55         p=p->pNext;
56     temp=p->pNext;
57     if(temp){
58         p->pNext=temp->pNext;
59         free(temp);  
60     }
61 }
62 /*
63 int i;i为节点位置,从1开始.
64 */
65 void Insert(const pNODE head,int data,unsigned int i){
66     pNODE p=head,temp;
67     while(i>1&&--i&&p->pNext)
68         p=p->pNext;
69     temp=(pNODE)malloc(sizeof(NODE));
70     assert(temp);
71     temp->data=data;
72     temp->pNext=p->pNext;
73     p->pNext=temp;
74 }
75 int main(){
76     pNODE head=NULL;
77     head=Create();
78     Insert(head,1,1);
79     Insert(head,2,1);
80     Insert(head,3,1);
81     Insert(head,4,1);
82     Insert(head,5,0);
83     Insert(head,6,6);
84     Insert(head,9,100);
85     Visit(head);
86     printf("\n");
87     DeleteValue(head,3);//删除值为3的节点
88     Visit(head);  
89     printf("\n");  
90     Delete(head,7);//删除第7个节点,失败,无任何节点删除.
91     Visit(head); 
92     printf("\n");  
93     Delete(head,5);//删除第5个节点,成功.第5个节点值为6.
94     Visit(head);
95     printf("\n");  
96     return 0;
97 }

代码通过验证.

http://ideone.com/GjFayz

posted @ 2017-03-10 09:53  夜梦多离殇  阅读(170)  评论(0编辑  收藏  举报