TheAlgorithms-C-Plus-Plus/Operations on Datastructures/Reverse a Linked List using Recusion.cpp

77 lines
792 B
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-12-24 01:30:49 +08:00
using namespace std;
struct node
{
int val;
node *next;
};
node *start;
void insert(int x)
{
2019-08-21 10:10:08 +08:00
node *t = start;
if (start != NULL)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
while (t->next != NULL)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
t = t->next;
2017-12-24 01:30:49 +08:00
}
2019-08-21 10:10:08 +08:00
node *n = new node;
t->next = n;
n->val = x;
n->next = NULL;
2017-12-24 01:30:49 +08:00
}
else
{
2019-08-21 10:10:08 +08:00
node *n = new node;
n->val = x;
n->next = NULL;
start = n;
2017-12-24 01:30:49 +08:00
}
}
void reverse(node *p, node *q)
{
if (q->next == NULL)
{
2019-08-21 10:10:08 +08:00
q->next = p;
p->next = NULL;
start = q;
2017-12-24 01:30:49 +08:00
return;
}
else
{
reverse(q, q->next);
2019-08-21 10:10:08 +08:00
q->next = p;
p->next = NULL;
2017-12-24 01:30:49 +08:00
}
}
void show()
{
2019-08-21 10:10:08 +08:00
node *t = start;
while (t != NULL)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
cout << t->val << "\t";
t = t->next;
2017-12-24 01:30:49 +08:00
}
}
int main()
{
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
insert(6);
reverse(start, start->next);
show();
return 0;
}