要创建链表并输入数据,可以按照以下步骤进行:
- 首先定义一个节点结构体,包含一个数据域和一个指向下一个节点的指针域。例如:
struct Node { int data; struct Node* next; };
- 定义一个头指针指向链表头部。初始化为NULL,表示链表为空。例如:
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#include 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; }
这样就完成了创建链表并输入数据的操作。