forked from usamajay/hacktoberfest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseLinkedList.cpp
74 lines (73 loc) · 1.23 KB
/
ReverseLinkedList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next;
node(int data)
{
this->data = data;
next = NULL;
}
};
void print(node *head)
{
node *temp = head;
while (temp)
{
cout << temp->data << " ";
temp = temp->next;
}
}
node *takeInput()
{
int data;
cin >> data;
node *head = NULL;
while (data != -1)
{
node *newnode = new node(data);
if (head == NULL)
head = newnode;
else
{
node *temp = head;
while (temp->next)
{
temp = temp->next;
}
temp->next = newnode;
}
cin >> data;
}
return head;
}
node *Reverse(node *head)
{
//Base Condition
if (head == NULL || head->next == NULL)
{
return head;
}
//Recursion Call
node *smallAns = Reverse(head->next);
//Small Calculations
node *temp = smallAns;
while (temp->next)
{
temp = temp->next;
}
temp->next = head;
head->next = NULL;
return smallAns;
}
int main()
{
node *head, *tail;
head = takeInput();
print(head);
cout << endl;
tail = Reverse(head);
print(tail);
}