个数据和一个指向下一个结构体变量的指针,
依靠这些指针将所有的结构体变量连接成一个链表。
例:建立和输出一个简单的链表
Struct student
{
Long num;
Char name[20];
Struct student *next;
};
Main(){
Struct student a,b,c,*head,*p;
A.num=2002001;b.num=2002002;c.num=2002003;
Strcpy(a.name,”zhang”);
Strcpy(b.name,”sun”);
Strcpy(c.name,”li”);
Head=&a;
A.next=&b;
B.Next=&c;
C.Next=NULL;
P=head;
Do
{
Printf(“%ld,%s”,p->num,p->name);
P=p->next;
}while(p!=NULL);
}
链表的基本操作
链表的基本操作包括建立动态链表、链表的插入、删除、输出和查找等。
1.建立动态链表
所谓建立动态链表是指一个一个地输入各结点数据,并建立起各结点前后相链的关系。建立动态链表有两种方式:一种是在链表尾插入节点,一种是在链表头插入结点。
例:写一个函数建立一个若干学生数据的单向动态链表。(要求按学号从小到大的顺序建立)
#define NULL 0
Struct student
{
Long num;
Struct student *next;
};
Struct student *creat()
{
Struct student *head,*p,*q;
Long x;
q=head=(struct student *)malloc(sizeof(struct student));
Head->next=NULL;
Printf(“\nplease input datas to the list:”);
Scanf(“%ld”,&x);
While(x!=0){
P=(struct student *)malloc(sizeof(struct student));
P->num=x;
P->next=NULL;
q->next=p;
q=p;
Scanf(“%ld”,&x);
}
Return (head);
}
2.输出链表
Void print(struct student *head)
{
Struct student *p;
P=head->next;
Printf(“\nthe list is:”);
If(p==NULL)
Printf(“the list is NULL!\n”);
While(p!=NULL)
{
Printf(“%6ld”,p->num);
P=p->next;
}
Printf(“\n”);
}
3.删除链表中的一个结点
Void del(struct student *head)
{
Struct student *p,*q;
Long num;
Printf(“\nplease input the student’ num you want to delete:”);
Scanf(“%ld”,&num);
P=head->next;
While(num!=p->num && p->next!=NULL){
Q=p;
P=p->next;
}
If(num==p->num)
{q->next=p->next;
Free(p);}else
Printf(“\n%ld is not found!\n”,num);
}
4.在链表中插入一个结点
Void insert(struct student *head)
{
Struct student *p,*q,*t;
P=(struct student *)malloc(sizeof(struct student));
Printf(“\nplease input the student you want to insert:”);
Scanf(“%ld”,&p->num);
Q=head;
While(q-next!=NULL && q->next-num
num)
Q=q->next;
P->next=q->next;
Q->next=p;
}
5.对链表的综合操作
Void main(){
Struct student *la;
La=creat();
Print(la);
Del(la);
Print(la);
Insert(la);
Print(la);
}
链表与结构体数组的主要区别
1、数组的元素个数是固定的,而组成链表的结点个数可按需要增减;
2、数组中的元素顺序关系由元素在数组中的位置(即下标)确定,链表中的结点顺序关系由结点所包含的指针来体现。
3、对于不是固定长度的列表,用可能最大长度的数组来描述,会浪费许多内存空间。另外,对于元素的插入、删除操作非常频繁的列表处理场合,用数组表示
列表也是不适宜的。若用链表实现,会使程序结构清晰,处理的方法也较为简单。
枚举类型
字符型或其它类型显然是不妥当的。为此,C语言提供了一种称为“枚举”的类型。在“枚举”类型的定义中列举出所有可能的取值,被说明为该“枚举”类型的变量取值不能超过定义的范围。应该说明的是,枚举类型是一种基本数据类型,而不是一种构造类型,因为它不能再分解为任何基本类型。
枚举类型的定义和枚举变量的说明:
1、枚举的定义枚举类型定义的一般形式为:
enum枚举名{枚举值表};
在枚举值表中应罗列出所有可用值。这些值也称为枚举元素。例如:
该枚举名为weekday,枚举值共有7个,即一周中的七天。凡被说明为weekday类型变量的取值只能是七天中的某一天。
2、枚举变量的说明
如同结构和联合一样,枚举变量也可用不同的方式说明,即先定义后说明,同时定义说明或直接说明。设有变量a,b,c被说明为上述的weekday,可采用下述任一种方式:
enumweekday{sun,mou,tue,wed,thu,fri,sat};
enumweekdaya,b,c;
或者为:
enumweekday{sun,mou,tue,wed,thu,fri,sat}a,b,c;
或者为:
enum{sun,mou,tue,wed,thu,fri,sat}a,b,c;
枚举类型变量的赋值和使用
枚举类型在使用中有以下规定:
1、枚举值是常量,不是变量。不能在程序中用赋值语句再对它赋值。例如对枚举weekday的元素再作以下赋值:
sun=5;mon=2;sun=mon;都是错误的。
2、枚举元素本身由系统定义了一个表示序号的数值,从0开始顺序定义为0,1,2…。如在weekday中,sun值为0,mon值为1,…,sat值为6。
main(){
enumweekday
{sun,mon,tue,wed,thu,fri,sat}a,b,c;
b=mon;
c=tue;
printf("%d,%d,%d",a,b,c);}
说明