/*=============================================================
目的:动态链表的综合操作
算法分析:1、构造第一个结构体作为头
2、以P2和P1为游码在结构体移动
3、 p1负责存储新创立的结构体,p2负责指向新创立的结构体
4、creat函数返回链表的头
==============================================================
作者:最后的村长
时间:2009年12月21日
工具:DEV C++ 4.9.9.2
version:1.0
==============================================================*/
#include <stdio.h>
#include <stdlib.h>
//#define NULL 0
#define LEN sizeof(struct student)
struct student
{
long num;
int score;
struct student *next;
};//学生结构体定义,包含两个数据:学号和成绩
int n;//n为全局变量,实现链表中元素个数的统计
struct student *create(void)//开辟动态链表函数
{
struct student *head;
struct student *p1,*p2;
n=0;
long int stu_id=1100;
p1=p2=(struct student *)malloc(LEN);//
p1->num=stu_id;
printf("请输入1个学生的成绩:\n");
scanf("%d",&(p1->score));//第一个学生结构体创立结束
head=NULL;
while(p1->score!=0)
{
n=n+1;//统计链表中结构体元素的个数
if(n==1)head=p1;//头指针赋值
else p2->next=p1;//前一个结构体的next指向下一个结构体
//!注意上面语句的执行顺序
p2=p1;//p2移向下一个结构体
p1=(struct student *)malloc(LEN);//新开辟一个结构体内存单元
p1->num=++stu_id;//对新开辟的结构体内元素初始化
printf("请输入%d个学生的成绩:\n",n+1);
printf("成绩:");
scanf("%d",&(p1->score));
}
p2->next=NULL;
return head;
}
/*=============================================================*/
void print(struct student *head)
{
struct student *p;
printf("\n一共是 %d 的学生成绩如下 :\n",n);
p=head;
if(head!=NULL)
do
{
printf("%ld,%d\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
int main()
{
struct student *p,*head;
head=create();
//printf("%ld,%d\n",head->num,head->score);
print(head);
system("PAUSE");
return 0;
}
|
代码在写完编译结束后,并没有任何的错误,但是运行产生的结果却不是自己希望的结果,如何在代码中建立适当的逻辑结构呢???
编译器更多的是从语法的角度考虑问题,不是从逻辑的角度分析的!难道只能通过人的检查才能发现问题的所在吗?如果是几千几万行代码呢,看来程序的注释的编写时非常有必要的!!!!
阅读(557) | 评论(0) | 转发(0) |