gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
写一个创建链表的程序用c语言
- User
写一个创建链表的程序用c语言
- Assistant
#include <stdio.h> #include <stdlib.h>
// 定义链表节点结构体 struct Node { int data; struct Node* next; };
// 函数声明 struct Node* createLinkedList(int n); void displayLinkedList(struct Node* head);
int main() { int n; printf("请输入链表节点个数:"); scanf("%d", &n); struct Node* head = createLinkedList(n);
printf("创建的链表为:"); displayLinkedList(head); return 0;}
// 创建链表函数 struct Node* createLinkedList(int n) { int i, data; struct Node *head, *newNode, *temp;
head = NULL; // 根据节点个数依次创建链表节点并连接起来 for (i = 0; i < n; i++) { // 创建新节点 newNode = (struct Node*)malloc(sizeof(struct Node)); // 输入节点数据 printf("请输入第 %d 个节点数据:", i+1); scanf("%d", &data); newNode->data = data; newNode->next = NULL; // 如果是第一个节点 if (head == NULL) { head = newNode; } else { // 如果不是第一个节点,则将当前节点连接到上一个节点的后面 temp->next = newNode; } // 更新 temp 为当前节点 temp = newNode; } return head;}
// 显示链表函数 void displayLinkedList(struct Node* head) { // 定义临时节点指针,用于遍历链表 struct Node* temp = head;