#include <stdio.h>\n#include <stdlib.h>\n\n// 定义链表节点结构体\ntypedef struct Node {\n int data;\n struct Node* next;\n} Node;\n\n// 创建新节点\nNode* createNode(int data) {\n Node* newNode = (Node*)malloc(sizeof(Node));\n if (newNode == NULL) {\n printf("内存分配失败\n");\n exit(1);\n }\n newNode->data = data;\n newNode->next = NULL;\n return newNode;\n}\n\n// 将节点插入到链表头部\nNode* insertFront(Node* head, int data) {\n Node* newNode = createNode(data);\n if (head == NULL) {\n head = newNode;\n } else {\n newNode->next = head;\n head = newNode;\n }\n return head;\n}\n\n// 打印链表\nvoid printList(Node* head) {\n Node* current = head;\n while (current != NULL) {\n printf("%d ", current->data);\n current = current->next;\n }\n printf("\n");\n}\n\n// 链表转置\nNode* reverseList(Node* head) {\n Node *prev = NULL;\n Node *current = head;\n Node next = NULL;\n \n while (current != NULL) {\n next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n \n head = prev;\n return head;\n}\n\nint main() {\n Node head = NULL;\n \n // 在链表头部插入节点\n head = insertFront(head, 5);\n head = insertFront(head, 4);\n head = insertFront(head, 3);\n head = insertFront(head, 2);\n head = insertFront(head, 1);\n \n printf("原链表:");\n printList(head);\n \n // 链表转置\n head = reverseList(head);\n \n printf("转置后的链表:");\n printList(head);\n \n return 0;\n}


原文地址: https://www.cveoy.top/t/topic/pRgO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录