-
Notifications
You must be signed in to change notification settings - Fork 0
/
headlist.c
100 lines (94 loc) · 1.18 KB
/
headlist.c
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
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int a;
struct node * next;
}node;
static int insert(node *n,int i,int data)
{
node *p=n->next;
node *t;
int j=1;
while(p&&j<i)
{
j++;
p=p->next;
}
if(!p||j>i)
return -1;
t = (node*)malloc(sizeof(node));
t->a = data;
t->next = p->next;
p->next = t;
return 0;
}
static int add(node *l,int data)
{
node *p = (node*)malloc(sizeof(node));
p->a = data;
p->next = l->next;
l->next = p;
return 0;
}
static int delete(node *l,int i)
{
node *p = l;
node *t;
int j=1;
while(p&&j<i)
{
j++;
p = p->next;
}
if(!p||j>i)
return -1;
t = p->next;
p->next = t->next;
free(t);
return 0;
}
static void destory(node *l)
{
node *p,*q=l->next;
while(q)
{
p = q->next;
free(q);
q=p;
}
l->next=NULL;
}
static void show(node *p)
{
node *l=p->next;
while(l)
{
printf("%d->",l->a);
l=l->next;
}
printf("\n");
}
int main()
{
node *l = (node*)malloc(sizeof(node));
l->next = NULL;
add(l,1);
add(l,2);
add(l,3);
add(l,4);
show(l);
if(insert(l,4,5)!=0)
{
printf("insert error\n");
}
if(delete(l,1)!=0)
{
printf("delete error!\n");
}
show(l);
destory(l);
show(l);
add(l,6);
show(l);
return 0;
}