在C語言中,遍歷一個結(jié)構(gòu)體定義的鏈表通常需要使用指針來訪問鏈表中的每個節(jié)點。以下是一個簡單的示例代碼片段,展示了如何遍歷一個包含整數(shù)元素的鏈表:
#include <stdio.h>
#include <stdlib.h>
// 定義鏈表節(jié)點的結(jié)構(gòu)體
struct Node {
int data; // 數(shù)據(jù)域,存儲整數(shù)
struct Node* next; // 指向下一個節(jié)點的指針
};
// 函數(shù)用于創(chuàng)建新的鏈表節(jié)點
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 函數(shù)用于遍歷鏈表并打印每個節(jié)點的數(shù)據(jù)
void traverseLinkedList(struct Node* head) {
struct Node* current = head; // 從頭節(jié)點開始遍歷
while (current != NULL) {
printf("%d ", current->data); // 打印當(dāng)前節(jié)點的數(shù)據(jù)
current = current->next; // 移動到下一個節(jié)點
}
printf("\n");
}
int main() {
// 創(chuàng)建鏈表節(jié)點
struct Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
// 遍歷鏈表并打印每個節(jié)點的數(shù)據(jù)
traverseLinkedList(head);
// 釋放鏈表內(nèi)存(可選)
struct Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
return 0;
}
在這個示例中,我們首先定義了一個名為Node
的結(jié)構(gòu)體,它包含一個整數(shù)類型的數(shù)據(jù)和一個指向下一個節(jié)點的指針。然后,我們創(chuàng)建了一個名為createNode
的函數(shù),用于動態(tài)分配內(nèi)存并初始化新節(jié)點。接著,我們編寫了一個名為traverseLinkedList
的函數(shù),該函數(shù)接受鏈表頭節(jié)點作為參數(shù),并使用一個循環(huán)來遍歷鏈表,同時打印每個節(jié)點的數(shù)據(jù)。最后,在main
函數(shù)中,我們創(chuàng)建了一個簡單的鏈表,并調(diào)用traverseLinkedList
函數(shù)來遍歷并打印鏈表中的元素。