需要将单链表倒序,并输出新的链表
核心代码
- Node *next = root->next;
- root->next = new_root;
- new_root = root;
- root = next;
- #include <stdio.h>
- typedef struct Node {
- char data;
- struct Node* next;
- } Node;
- void print_list(Node* root) {
- while (root) {
- printf("%c ", root->data);
- root = root->next;
- }
- printf("\n");
- }
- Node* reverse(Node* root) {
- Node* new_root = NULL;
- while (root) {
- Node* next = root->next;
- root->next = new_root;
- new_root = root;
- root = next;
- }
- return new_root;
- }
- int main() {
- Node f = { 'f', NULL };
- Node e = { 'e', &f };
- Node d = { 'd', &e };
- Node c = { 'c', &d };
- Node b = { 'b', &c };
- Node a = { 'a', &b };
- Node* root = &a;
- print_list(root);
- root = reverse(root);
- print_list(root);
- return 0;
- }
本文介绍了一种简单的单链表倒序算法,并通过C语言实现了该算法。首先定义了链表节点结构,接着提供了打印链表和倒序链表的函数。最后,通过实例演示了如何使用这些函数完成链表的创建、打印、倒序及再次打印。
1709

被折叠的 条评论
为什么被折叠?



