Data Structure Linked List: Write a function to reverse a linked list

本文详细介绍了如何使用递归方法反转一个链表。通过给出的代码示例,逐步解释了每一行代码的作用,包括节点创建、链表打印、递归反转过程等关键步骤。

iterative太简单不写了

http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <queue>
 5 #include <stack>
 6 #include <string>
 7 #include <fstream>
 8 #include <map>
 9 #include <set>
10 using namespace std;
11 
12 struct node {
13     int data;
14     node *next;
15     node() : data(0), next(NULL) { }
16     node(int d) : data(d), next(NULL) { }
17 };
18 
19 void push(node* &head, int k) {
20     node *new_node = new node(k);
21     new_node->next = head;
22     head = new_node;
23 }
24 
25 void print(node *head) {
26     while (head) {
27         cout << head->data << " ";
28         head = head->next;
29     }
30     cout << endl;
31 }
32 
33 void reverselist(node *&head) {
34     if (!head) return;
35     node *cur = head;
36     node *next = head->next;
37     if (!next) return;
38     reverselist(next);
39     cur->next->next = cur;
40     cur->next = NULL;
41     head = next;
42 }
43 
44 int main() {
45     node *head = NULL;
46     push(head, 5);
47     push(head, 4);
48     push(head, 3);
49     push(head, 2);
50     push(head, 1);
51     print(head);
52     reverselist(head);
53     print(head);
54     return 0;
55 }

 

转载于:https://www.cnblogs.com/yingzhongwen/p/3655612.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值