-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverseLinkedList.cpp
104 lines (95 loc) · 1.99 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
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
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node()
{
Node(0);
}
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
class Singlylinkedlist
{
public:
Node * head;
Singlylinkedlist()
{
this->head =nullptr;
}
void insertatlast(int data)
{
Node* newnode =new Node(data);
if(head==NULL)
{
head=newnode;
}
else
{
Node *p=head;
while(p->next!=NULL)
{
p=p->next;
}
p->next=newnode;
}
}
void reverseIter()
{
Node* curr =head;
Node *prev =NULL,*next=NULL;
while(curr!=NULL)
{
next=curr->next;
//reverse curr pointer
curr->next=prev;
//move pointers one position forward
prev=curr;
curr=next;
}
head=prev;
}
Node* reverserecur(Node *curr)
{
if(curr==NULL || curr->next==NULL)
{
return curr;
}
Node* head = reverserecur(curr->next);
curr->next->next=curr;
curr->next=NULL;
return head;
}
void printlist()
{
if(head==NULL)
cout<<"Linked list is empty"<<endl;
Node *p=head;
while(p!=NULL)
{
cout<<p->data<<"->";
p=p->next;
}
cout<<"\n";
}
};
int main()
{
Singlylinkedlist sll;
for(int i=5;i>0;i--)
{
sll.insertatlast(i);
}
sll.printlist();
sll.reverseIter();
// sll.printlist();
sll.reverserecur(sll.head);
sll.printlist();
return 0;
}