forked from akshitagit/CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse a link list
56 lines (50 loc) · 879 Bytes
/
Reverse a link list
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
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
//constructor
Node(int data){
this->data= data;
next= NULL;
}
};
Node* reverse(Node* head){
Node* curr= head;
Node* prev= NULL;
Node* next= NULL;
while(curr){
next= curr->next;
curr->next= prev;
prev= curr;
curr= next;
}
//prev becomes the new head
return prev;
}
int main(){
int n; //enter the length of the link list
cin>>n;
Node* head=NULL;
Node* tail=NULL;
for(int i=0;i<n;i++){
int node; //values of the link list from the user
cin>>node;
Node* newnode= new Node(node);
if(head==NULL){
head= newnode;
tail= newnode;
}
else{
tail->next= newnode;
tail= newnode;
}
}
Node* nhead=reverse(head);
//reversed link list
while(!nhead){
cout<<nhead->data<<" ";
nhead= nhead->next;
}
return 0;
}