单链表倒序

本文介绍了一种简单的单链表倒序算法,并通过C语言实现了该算法。首先定义了链表节点结构,接着提供了打印链表和倒序链表的函数。最后,通过实例演示了如何使用这些函数完成链表的创建、打印、倒序及再次打印。

需要将单链表倒序,并输出新的链表

核心代码

  1. Node *next = root->next;
  2. root->next = new_root;
  3. new_root = root;
  4. root = next;

  1. #include <stdio.h>  
  2.   
  3. typedef struct Node {  
  4.   char data;  
  5.   struct Node* next;  
  6. } Node;  
  7.   
  8. void print_list(Node* root) {  
  9.   while (root) {  
  10.     printf("%c ", root->data);  
  11.     root = root->next;  
  12.   }  
  13.   printf("\n");  
  14. }  
  15.   
  16. Node* reverse(Node* root) {  
  17.   Node* new_root = NULL;  
  18.   while (root) {  
  19.     Node* next = root->next;  
  20.     root->next = new_root;  
  21.     new_root = root;  
  22.     root = next;  
  23.   }  
  24.   return new_root;  
  25. }  
  26.   
  27. int main() {  
  28.   Node f = { 'f', NULL };  
  29.   Node e = { 'e', &f };  
  30.   Node d = { 'd', &e };  
  31.   Node c = { 'c', &d };  
  32.   Node b = { 'b', &c };  
  33.   Node a = { 'a', &b };  
  34.   
  35.   Node* root = &a;  
  36.   print_list(root);  
  37.   root = reverse(root);  
  38.   print_list(root);  
  39.   
  40.   return 0;  
  41. }  

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值