-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathReverseLinkedList.cpp
115 lines (85 loc) · 1.8 KB
/
ReverseLinkedList.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// { Driver Code Starts
//Initial Template for C++// C program to find n'th Node in linked list
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
/* Link list Node */
struct Node {
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
// } Driver Code Ends
/* Linked List Node structure:
struct Node
{
int data;
struct Node *next;
}
*/
class Solution
{
public:
//Function to reverse a linked list.
struct Node* reverseList(struct Node *head)
{
Node* follow;
Node* prev;
Node* temp;
temp = head;
follow = temp->next;
temp->next = NULL;
prev= temp;
temp = follow;
while (temp != NULL)
{
follow= temp->next;
temp->next = prev;
prev= temp;
temp = follow;
}
head = prev;
return head;
}
};
// { Driver Code Starts.
void printList(struct Node *head)
{
struct Node *temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* Driver program to test above function*/
int main()
{
int T,n,l,firstdata;
cin>>T;
while(T--)
{
struct Node *head = NULL, *tail = NULL;
cin>>n;
cin>>firstdata;
head = new Node(firstdata);
tail = head;
for (int i=1; i<n; i++)
{
cin>>l;
tail->next = new Node(l);
tail = tail->next;
}
Solution ob;
head = ob. reverseList(head);
printList(head);
cout << endl;
}
return 0;
}
// } Driver Code Ends