题解 | #牛牛的单向链表#
牛牛的单向链表
https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4
#include <stdio.h> #include <stdlib.h> // 定义链表节点结构 struct ListNode { int val; struct ListNode *next; }; // 创建一个新的链表节点 struct ListNode* createNode(int val) { struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val = val; newNode->next = NULL; return newNode; } // 打印链表 void printList(struct ListNode *head) { struct ListNode *current = head; while (current != NULL) { printf("%d ", current->val); current = current->next; } printf("\n"); } int main() { int n; // 输入数组的长度 scanf("%d", &n); // 输入数组的值 int *arr = (int *)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } // 创建链表 struct ListNode *head = NULL; struct ListNode *tail = NULL; for (int i = 0; i < n; i++) { struct ListNode *newNode = createNode(arr[i]); if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } } // 打印链表 printList(head); // 释放内存 struct ListNode *current = head; while (current != NULL) { struct ListNode *temp = current; current = current->next; free(temp); } free(arr); return 0; }