要創建鏈表并輸入數據,可以按照以下步驟進行:
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
printf("請輸入數據:");
scanf("%d", &(newNode->data));
if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
重復步驟3到步驟5,直到輸入完所有數據。
遍歷鏈表,輸出所有節點的數據。例如:
struct Node* temp = head;
printf("鏈表數據:");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
struct Node* temp = head;
while (temp != NULL) {
struct Node* nextNode = temp->next;
free(temp);
temp = nextNode;
}
完整的代碼示例:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = NULL;
int n;
printf("請輸入鏈表長度:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
printf("請輸入數據:");
scanf("%d", &(newNode->data));
if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
struct Node* temp = head;
printf("鏈表數據:");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
temp = head;
while (temp != NULL) {
struct Node* nextNode = temp->next;
free(temp);
temp = nextNode;
}
return 0;
}
這樣就完成了創建鏈表并輸入數據的操作。