http://www.oschina.net/code/snippet_252667_27314#comments
这个代码有很多错误,估计是从老谭书上抄来但是很多还抄错了:对照老谭的书好好研究下。切记!
p2是p1的跟屁虫!切记
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
|
#include"stdio.h" #include"malloc.h" struct
stu
{ int
num; //这个是学号
float
score; //这个是分数
struct
stu *next;
}; struct
stu*create()
{ int
n; //这个n这里不大合适 ,最好弄个全局的
struct
stu *head,*p1,*p2;
p1=p2=( struct
stu*) malloc ( sizeof ( struct
stu));
scanf ( "%d %f" ,&p1->num,&p1->score);
head=NULL;
n=0;
while (p1->num!=0)
{
n++;
if (n==1)head=p1;
else
{
p2->next=p1;
p2=p1;
p1=( struct
stu*) malloc ( sizeof ( struct
stu));
scanf ( "%d %f" ,&p1->num,&p1->score);
}
}
p2->next=NULL;
return
head;
}; //难点在插入操作的实现上(默认从小到大排列的) struct
stu *insert( struct
stu *head, struct
stu *stud)
{ struct
stu *p0,*p1,*p2;
p1=head;
p0=stud;
while ((p0->num>p1->num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if (p0->num<p1->num) //能在队列中插入(不是尾巴)
{
if (head==p1)head=p0; //在头部前插入
else //在非头部插入
{
p2->next=p0;
p0->next=p1;
}
}
else //在尾巴插入
{
p1->next=p0;
p0->next=NULL;
}<br> <span style= "color: rgb(255, 0, 0);" > //这个地方要怎么维护总的num呢 ?</span>
return
head;
}; //删除操作难度次之 struct
stu *del( struct
stu *head, int
num)
{ struct
stu *p1,*p2;
p1=head;
if (head!=NULL)
{
while ((p1->num<num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if (num==p1->num) //找到节点了
{ //这里要考虑删除头节点的情况
p2->next=p1->next;
p2=p1;<br> //要考虑删除的节点内存释放<br> //要考虑维护n的数目<br>
}
else //没有找到节点
{
printf ( "NO Result!!!\n" );
}
}
else
printf ( "The linklist is EMPTY\n" );
return
head;
}; void
print( struct
stu *head)
{ struct
stu *p;
p=head;
while (p)
{
printf ( "%d %f\n" ,p->num,p->score);
p=p->next;
}
} void
main()
{ int
n;
struct
stu *create();
struct
stu *insert( struct
stu *head, struct
stu *stud);
void
print( struct
stu *head);
struct
stu *head,*p,*p1;
head=create();
p=head;
print(p);
printf ( "please input :\n" );
scanf ( "%d %f" ,&p1->num,&p1->score);
p=insert(head,p1);
print(p);
printf ( "please input the del num:\n" );
scanf ( "%d" ,&n);
p=del(head,n);
print(p);
} |