静态链表是用数组实现的,是顺序的存储结构,在物理地址上是连续的,而且需要预先分配大小。动态链表是用申请内存函数(C是malloc,C++是new)动态申请内存的,所以在链表的长度上没有限制。动态链表因为是动态申请内存的,所以每个节点的物理地址不连续,要通过指针来顺序访问。
*所有结点都是在程序中定义的,不是临时开辟的,也不能用完后释放,这种链表称为“静态链表”。*/
struct Student
{
int num;
float score;
struct Student *next;
};
int main()
{
struct Student stu1, stu2, stu3, *head, *p;
stu1.num = 1001; stu1.score = 80;
stu2.num = 1002; stu2.score = 85;
stu3.num = 1003; stu3.score = 90;
head = &stu1;
stu1.next = &stu2;
stu2.next = &stu3;
stu3.next = NULL;
p = head;
do{
printf("%d,%f\n", p->num, p->score);
p = p->next;
} while (p != NULL);
system("p
- 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
- 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
*所谓动态链表,是指在程序执行过程中从无到有地建立起一个链表,即一个一个地开辟结点和输入各结点数据,并建立起前后相链的关系。*/
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;
while (p1->No != 0)
{
n++;
if (n == 1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
printf("请输入学号,输入0终止:\n");
p1 = (struct Student *)malloc(sizeof(struct Student));
scanf("%d", &p1->No);
};
p2->next = NULL;
struct Student *p;
p = head;
while (p != NULL)
{
printf("%d,", p->No);
p = p -> next;
}
printf("\n");
system("pause");
}