数据结构之单向链表

基础数据结构之单向链表

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
//
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct node)
struct node
{
int num;
struct node*next;
};
int n=0;
struct node*()
{
struct node*head,*p1,*p2;
head=NULL ;
p1=p2=(struct node*)malloc(LEN);
printf("please put in data:n");
scanf_s("%d",&p1->num);
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct node*)malloc(LEN);
printf("please put in data:n");
scanf_s("%d",&p1->num);
}
p2->next=NULL;
return head;
}
void print(struct node*head)
{
struct node*p=head;
while(p!=NULL)
{
printf("%dt",p->num);
p=p->next;
}
}
void clear(struct node*head)
{
struct node*p1,*p2;
p1=p2=head;
while(p1!=NULL)
{
p1=p2->next;
free(p2);
p2=p1;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
struct node*p=NULL;
int i;
printf("tt1.创建链表n");
printf("tt2.输出链表n");
printf("tt3.清空链表n");
while(1)
{
printf("请输入:n");
scanf_s("%d",&i);
switch(i)
{
case 1:p=create();printf("创建成功n");break;
case 2:print(p);break;
case 3:clear(p);break;
default:return 0;
}
}
return 0;
}