要创建链表并输入数据,可以按照以下步骤进行:
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;
}
这样就完成了创建链表并输入数据的操作。