静态链表和动态链表是线性表链式存储结构的两种不同的表示方式。
?
静态链表的初始长度一般是固定的,在做插入和删除操作时不需要移动元素,仅需修改指针,故仍具有链式存储结构的主要优点。
?
动态链表是相对于静态链表而言的,一般地,在描述线性表的链式存储结构时如果没有特别说明即默认描述的是动态链表。
?
下面给出它们的简单实现,关于线性表更为详尽的
C语言的实现,可以参考 http://www.cnblogs.com/choon/p/3876606.
html
?
静态链表
?
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#include
#include
/*所有结点都是在程序中定义的,不是临时开辟的,也不能用完后释放,这种链表称为“静态链表”。*/
struct Student
{
? ? int num;
? ? float score;
? ? struct Student *next;
};
int main()
{
? ? struct Student stu1, stu2, stu3, *head, *p;
? ? stu1.num = 1001; stu1.score = 80; //对结点stu1的num和score成员赋值
? ? stu2.num = 1002; stu2.score = 85; //对结点stu2的num和score成员赋值
? ? stu3.num = 1003; stu3.score = 90; //对结点stu3的num和score成员赋值
?
? ? head = &stu1; ? ? ?//头指针指向第1个结点stu1
? ? stu1.next = &stu2; //将结点stu2的地址赋值给stu1结点的next成员
? ? stu2.next = &stu3; //将结点stu3的地址赋值给stu2结点的next成员
? ? stu3.next = NULL; ?//stu3是最后一个结点,其next成员不存放任何结点的地址,置为NULL
? ? p = head; ? ? ? ? ?//使p指针也指向第1个结点
?
? ? //遍历静态链表
? ? do{
? ? ? ? printf("%d,%f\n", p->num, p->score); //输出p所指向结点的数据
? ? ? ? p = p->next; ? ? ? ? ? ? ? ? ? ? ? ? //然后让p指向下一个结点
? ? } while (p != NULL); ? ? ? ? ? ? ? ? ? ? //直到p的next成员为NULL,即完成遍历
?
? ? system("pause");
}
?
?
动态链表
?
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#include
#include
/*所谓动态链表,是指在程序执行过程中从无到有地建立起一个链表,即一个一个地开辟结点和输入各结点数据,并建立起前后相链的关系。*/
struct Student
{
? ? int No;//学号
? ? struct Student *next;
};
int main()
{
? ? struct Student *p1, *p2, *head;
? ? int n = 0; //结点个数
? ? head = NULL;
? ? p1 = (struct Student *)malloc(sizeof(struct Student));
? ? printf("请输入1个学号\n");
? ? scanf("%d", &p1->No);
? ? p2 = p1; //开始时,p1和p2均指向第1个结点
? ? while (p1->No != 0)
? ? {
? ? ? ? n++;
? ? ? ? if (n == 1)
? ? ? ? {
? ? ? ? ? ? head = p1;
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? p2->next = p1;
? ? ? ? }
? ? ? ? p2 = p1;//p2是最后一个结点
? ? ? ? printf("请输入学号,输入0终止:\n");
? ? ? ? p1 = (struct Student *)malloc(sizeof(struct Student));
? ? ? ? scanf("%d", &p1->No);
? ? };
? ? p2->next = NULL;//输入完毕后,p2->next为NULL
?
? ? //遍历动态链表
? ? struct Student *p;
? ? p = head;
? ? while (p != NULL)
? ? {
? ? ? ? printf("%d,", p->No);
? ? ? ? p = p -> next;
? ? }
? ? printf("\n");
?
? ? system("pause");
}