-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse.cpp
77 lines (63 loc) · 1.32 KB
/
reverse.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
#include <iostream>
using namespace std;
//this program is to reverse linked list
class node
{
public:
int data;
node *next;
};
void push(node **head_ref, int new_data)
{
node *new_node = new node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(node *i)
{
while (i != NULL)
{
cout << i->data << " ";
i = i->next;
}
cout<<endl;
}
//iterative method
node* reverse(node* &head){
node* prevptr = NULL;
node* currptr = head;
node* nextptr;
while(currptr != NULL){
nextptr = currptr->next;
currptr->next = prevptr;
prevptr = currptr;
currptr = nextptr;
}
return prevptr;
}
//recursive method
node* reverseRecursive(node* &head){
if(head == NULL || head->next==NULL){
return head;
}
node* newhead = reverseRecursive(head->next);
head->next->next = head;
head->next = NULL;
return newhead;
}
int main()
{
node *head = NULL;
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printList(head); //1 2 3 4 5
node* newhead = reverse(head);
printList(newhead); // 5 4 3 2 1
node* recurrsiveHead = reverseRecursive(newhead);
printList(recurrsiveHead); //1 2 3 4 5
return 0;
}