-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathReverse_a_linked_list.cpp
62 lines (62 loc) · 1.21 KB
/
Reverse_a_linked_list.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
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node* next;
node(int d) {
data = d;
next = NULL;
}
};
void insertAtHead(node* &head, int value) {
node* temp = new node(value);
if(head == NULL) {
head = temp;
return;
}
node* curr = head;
while(curr->next != NULL)
curr = curr->next;
curr->next = temp;
}
void printList(node* head) {
node* curr = head;
while(curr != NULL) {
cout<<curr->data<<" ";
curr = curr->next;
}
cout<<endl;
}
node* reverse(node* &head) {
node* prev = NULL;
node* curr = head;
node* next;
while(curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main()
{
int n;
cout<<"Enter the number of nodes in the linked list:";
cin>>n;
int x;
cout<<"Enter the nodes:";
cin>>x;
node* head = new node(x);
for(int i=1;i<n;i++) {
cin>>x;
insertAtHead(head,x);
}
cout<<"The Original Linked List is: ";
printList(head);
head = reverse(head);
cout<<"The Linked List after reversal is: ";
printList(head);
return 0;
}