-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreverse_linkedList.cpp
More file actions
75 lines (65 loc) · 1.13 KB
/
Copy pathreverse_linkedList.cpp
File metadata and controls
75 lines (65 loc) · 1.13 KB
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
//Reverse a Linked List [OPTIMISED]
#include<iostream>
using namespace std ;
struct Node
{
int data;
Node *next;
Node(int data)
{
this->data=data;
this->next=NULL;
}
};
void printList(Node *head)
{
Node *p=head;
while(p!=NULL)
{
cout<<p->data<<" -> ";
p=p->next;
}
cout<<"\n";
}
void reverseList(Node* &head)
{
//This is an optimised (both space and time) method as this reverses links
Node *prev=NULL;
Node *curr=head;
Node *next;
while(curr!=NULL)
{
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
head=prev;
}
int main()
{
//number of nodes taking as input
int n;
cin>>n;
Node *head=NULL;
Node *tail=NULL;
for(int i=0;i<n;i++)
{
//this is to take input of n nodes
int x;
cin>>x;
Node *temp=new Node(x);
if(head==NULL)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}
reverseList(head);
printList(head);
}