在 C 语言中,链表是一种常用的数据结构。当我们想要遍历链表中的所有节点时,需要使用一个指针 p 来指向当前节点。

如果在遍历前没有将 p 指向链表的头节点 head,则 p 将无法访问链表中的任何节点。因此,在遍历链表之前,需要将 head 赋值给 p,即 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));
  scanf("%d%s%lf", &a->num, a->name, &a->score);
  scanf("%d%s%lf", &b->num, b->name, &b->score);
  scanf("%d%s%lf", &c->num, c->name, &c->score);
  head = a;
  a->next = b;
  b->next = c;
  c->next = NULL;
  p = head;
  printf("%d,%s,%.2f\n", p->num, p->name, p->score);
  p = p->next;
  printf("%d,%s,%.2f\n", p->num, p->name, p->score);

  // 如果不执行 `p=head`,则无法在后续代码中通过 `p` 来遍历整个链表。
  // 因为 `p` 没有指向链表的头节点,它无法遍历整个链表。

  return 0;
}

结论:

在遍历链表之前,必须将 head 赋值给 p,即 p=head,才能使 p 指向链表的头节点并进行遍历。

C语言链表遍历:p=head的作用解析

原文地址: https://www.cveoy.top/t/topic/oil4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录