TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
reverse_a_linked_list_using_recusion.cpp
1#include <iostream>
2using namespace std;
3
4struct node {
5 int val;
6 node *next;
7};
8
9node *start;
10
11void insert(int x) {
12 node *t = start;
13 if (start != NULL) {
14 while (t->next != NULL) {
15 t = t->next;
16 }
17 node *n = new node;
18 t->next = n;
19 n->val = x;
20 n->next = NULL;
21 } else {
22 node *n = new node;
23 n->val = x;
24 n->next = NULL;
25 start = n;
26 }
27}
28
29void reverse(node *p, node *q) {
30 if (q->next == NULL) {
31 q->next = p;
32 p->next = NULL;
33 start = q;
34 return;
35 } else {
36 reverse(q, q->next);
37 q->next = p;
38 p->next = NULL;
39 }
40}
41
42void show() {
43 node *t = start;
44 while (t != NULL) {
45 cout << t->val << "\t";
46 t = t->next;
47 }
48}
49
50int main() {
51 insert(1);
52 insert(2);
53 insert(3);
54 insert(4);
55 insert(5);
56 insert(6);
57
58 reverse(start, start->next);
59
60 show();
61
62 return 0;
63}
node * insert(node *root, int item)
inserts a new element into AVL tree
Definition avltree.cpp:92
struct node { int data; int height; struct node *left; struct node *right;} node
for std::queue
Definition avltree.cpp:13
int main()
Main function.