#include "stdio.h"
#include "stdlib.h"
//這里創建一個結構體用來表示鏈表的結點型別
struct node
{
int data;
struct node* next;
};
int main()
{
struct node* head, * p, * q, * t;
q = NULL;
int i, n, a;
scanf_s("%d", &n);
head = NULL;//頭指標初始為空
for (i = 1; i <= n; i++)//回圈讀入n個數
{
scanf_s("%d", &a);
//動態申請一個記憶體空間,用來存放一個結點,并用臨時指標p指向這個結點
p = (struct node*)malloc(sizeof(struct node));
p->data = a;//將資料存盤到當前結點的data域中
p->next = NULL;//設定當前結點的后繼指標指向空,也就是當前結點的下一個結點為空
if (head == NULL)
head = p;//如果這是第一個創建的結點,則將頭指標指向這個結點
else
q->next = p;//如果不是第一個創建的結點,則將上一個結點的后繼指標指向當前結點
q = p;//指標q也指向當前結點
}
//輸出鏈表中的所有數
t = head;
while (t != NULL)
{
printf("%d ", t->data);
t = t->next;//繼續下一個結點
}
getchar(); getchar();
return 0;
}
請問這段代碼中的第26行q->next = p,與27行 q= p有什么區別?
還有head = p這句代碼中,是把p這個結構指標的什么賦值給head指標了?
uj5u.com熱心網友回復:
q->next = p, 意思是把結點p添加到結點q的后面,q = p,意思是把指標q指向p,方便下一個回圈時添加。head = p注釋寫的很清楚了。如果實在理解不了,在紙上畫一下。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/69220.html
標籤:新手樂園
上一篇:資料異名 C++ 中 union 中使用 ⒖嫉膯栴}?
下一篇:即時通信中怎么實作一對一通信
