-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlinked_list_reversal.cpp
More file actions
44 lines (38 loc) · 872 Bytes
/
Copy pathlinked_list_reversal.cpp
File metadata and controls
44 lines (38 loc) · 872 Bytes
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
// Header File
#include<iostream>
using namespace std;
// Structure of Linked List
struct Node{
int data;
Node *next;
Node(int val){
data = val;
next = NULL;
}
};
// Utility function to print the linked list
void display(Node* head){
while(head != NULL){
cout<<head->data<<" ";
head = head->next;
}
cout<<"\n";
}
// Function to reverse the linked list recursively
Node* reverse(Node* head,Node* prev){
if(head == NULL)
return prev;
Node* next = head->next;
head->next = prev;
return reverse(next,head);
}
int main(){
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
cout<<"Original linked list "<<"\n";
display(head);
Node* newHead = reverse(head,NULL);
cout<<"Reversed Linked list "<<"\n";
display(newHead);
}