C语言链表操作:head 和 p 指针的顺序解析
C语言链表操作:head 和 p 指针的顺序解析
在C语言中,链表是一种常用的数据结构,它通过指针将一系列节点连接在一起。head 指针指向链表的头部,即第一个节点的地址。在本程序中,我们通过三个指针 a、b、c 分别分配了三个节点的内存空间,并将其连接起来,最后将头部指针 head 指向 a,即 a 为第一个节点。
p=head 表示将 p 指向第一个节点,即 a 节点。
为何不能反过来?
如果反过来,先执行 p=head,再执行 head=a,那么 p 指向的就是空地址(NULL),因为头部指针还没有被指向任何节点。
简而言之:
- 首先需要将
head指向第一个节点,才能将p指向head,以便访问链表中的节点。
错误示范:
#include <stdio.h>
#include <stdlib.h>
struct student {
int num;
char name[20];
double score;
struct student *next;
};
int main() {
struct student *a, *b, *c, *p, *head = NULL;
a = (struct student *)malloc(sizeof(struct student));
b = (struct student *)malloc(sizeof(struct student));
c = (struct student *)malloc(sizeof(struct student));
// 错误操作:先执行 p=head,再执行 head=a
p = head; // p 指向空地址
head = a; // head 指向 a
// ...其他操作...
return 0;
}
正确操作:
#include <stdio.h>
#include <stdlib.h>
struct student {
int num;
char name[20];
double score;
struct student *next;
};
int main() {
struct student *a, *b, *c, *p, *head = NULL;
a = (struct student *)malloc(sizeof(struct student));
b = (struct student *)malloc(sizeof(struct student));
c = (struct student *)malloc(sizeof(struct student));
// 正确操作:先执行 head=a,再执行 p=head
head = a; // head 指向 a
p = head; // p 指向第一个节点 (a)
// ...其他操作...
return 0;
}
总结:
在C语言链表操作中,head 指针的指向至关重要。必须先将 head 指向第一个节点,才能使用 p 指针访问链表中的节点。理解这一点对于正确操作链表至关重要。
原文地址: https://www.cveoy.top/t/topic/oikL 著作权归作者所有。请勿转载和采集!