-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrec_linkedlist.cpp
107 lines (94 loc) · 1.33 KB
/
rec_linkedlist.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head = NULL;
void create_list();
void display();
void display_rec(Node*);
void reverse_itr();
void reverse_rec(Node*);
int main()
{
create_list();
display();
reverse_rec(head);
display_rec(head);
return 0;
}
void create_list()
{
cout << "Enter the number of elements" << endl;
int num,i;
cin >> num;
Node *ptr = head;
for(i = 0;i<num;i++)
{
int k;
Node *temp = new Node();
cout << "Element " << i+1 <<endl;
cin >> k;
temp->data = k;
temp->next = NULL;
if (i == 0)
{
head = temp;
ptr = temp;
//delete temp;
}
else
{
ptr->next = temp;
ptr = ptr->next;
//delete temp;
}
}
}
void display()
{
//cout <<"Test"<<endl;
Node *temp = head;
while(temp != NULL)
{
cout << temp->data << endl;
temp = temp->next;
}
}
void reverse_itr()
{
Node *curr,*prev=NULL,*fwd;
curr = head;
fwd = curr->next;
bool t = true;
while(curr->next != NULL)
{
curr->next = prev;
prev = curr;
curr = fwd;
fwd = fwd->next;
}
curr->next = prev;
head = curr;
}
void display_rec(Node* p)
{
if (p == NULL)
return;
cout << p->data << endl;
display_rec(p->next);
}
void reverse_rec(Node* p)
{
if(p->next == NULL)
{
head = p;
return;
}
reverse_rec(p->next);
Node* q = p->next;
q->next = p;
p->next = NULL;
}