0%

c- 链表

1. 创建链表的结构体

1
2
3
4
5
6
7
8
9
#include<stdio.h>
#include<malloc.h>
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}linklist;
linklist *p,*head;

2. 删除、插入、查找、定位操作

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
114
115
116
117
118
119
120
121
//创建链表头插法 输出结果为逆置的 
linklist *createlist()
{
char ch;
int x;
linklist *s,*head;
head=NULL; //链表开始是为空 必须定义
ch=getchar();
while(ch!='*')
{
scanf("%d",&x);
s=(linklist*)malloc(sizeof(linklist));//保证s仅仅是一个节点
s->data=x; //书上源代码 s=malloc(sizeof(linklist));
s->next=head;
head=s;
ch=getchar();
}
return head;
}
//创建链尾头插法 输出结果为顺序的
linklist *creatlist()
{
char ch; //表示结束标志
int x;
linklist *head,*r,*s;
head=(linklist*)malloc(sizeof(linklist));
r=head;//主要是利用r进行操作
ch=getchar();
while(ch!='*')
{
scanf("%d",&x);
s=(linklist*)malloc(sizeof(linklist));
s->data=x;
r->next=s;

r=s;
ch=getchar();
}
r->next=NULL;//一定要将 r->next置空否则会出现无限循环
return (head);
}



//查找运算查找结点
linklist *lookpoint(linklist *head,int i)
{
int j=0;
linklist *p;
p=head;//从头结点(不存数据在第一个结点)开始 把head的地址传给p
while(p->next!=NULL&&j<i)
{
p=p->next;
j++;
}
if(i==j) return p;
else return NULL;
}
//查找运算,按值查找
linklist *lookkey(linklist *head,int key)
{
linklist *p;
p=head->next;//从开始结点(存数据在第二个结点) 开始
while(p!=NULL)
{
if(p->data!=key)
p=p->next;
else break;
}
return p;
}
//(后)插入运算,将新结点插入到*p结点之后
void insert(linklist *p,int x)
{
linklist *s;
s=(linklist *)malloc(sizeof(linklist));
//p=lookpoint(p,i);
s->data=x;
s->next=p->next;
p->next=s;
}
//查找与插入结合
void INSERT(linklist *p,int i,int x)
{
linklist *L;
int j;
j=i-1;
L=lookpoint(p,j);
insert(L,x);

}
// (前)插入运算,将新结点插入到*p结点之前
void beforeinser(linklist *p,int x)
{
linklist *s;
s=(linklist *)malloc(sizeof(linklist));//结点
s->data=p->data;
s->next=p->next;
p->data=x;
p->next=s;
}
//删去结点p的后继,首先用一个指针*r指向被删结点接着修改*p的指针域(next),最后释放结点*r
void deleter(linklist *p)
{
linklist *r; //指针
r=p->next;
p->next=r->next;
free(r);;
}
//打印链表
void print(linklist *head) //打印出链表head中各个结点的值
{
linklist *p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}

3.主函数设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
linklist *head,*p;
//创建链表
head=creatlist();
p=head;
print(head);
//寻找结点并插入
//INSERT(head,5,2);
head=lookpoint(head,2);
insert(head,5);
print(p);
//删除结点
head=p;
head=lookpoint(head,4);
deleter(head) ;
print(p);
return 0;
}

4. 测试结果