单链表倒序

来源:互联网 发布:linux快捷键退出终端 编辑:程序博客网 时间:2024/06/05 02:58

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

核心代码

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

[cpp] view plain copy
 
print?在CODE上查看代码片派生到我的代码片
  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. }  
0 0
原创粉丝点击