-
Notifications
You must be signed in to change notification settings - Fork 492
/
ReverseLinkedList.cpp
72 lines (63 loc) Β· 1.23 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
/*Program to reverse a linked list.*/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node * next;
Node(int data) {
this -> data = data;
next = NULL;
}
};
class LinkedList {
public:
Node * head;
LinkedList() {
head = NULL;
}
//Function to reverse the linked list
void reverse() {
Node * current = head;
Node * prev = NULL, * next = NULL;
while (current != NULL) {
next = current -> next;
current -> next = prev;
prev = current;
current = next;
}
head = prev;
}
//Function to print the linked list
void print() {
Node * temp = head;
while (temp != NULL) {
cout << temp -> data << " ";
temp = temp -> next;
}
}
//Function to Insert values to Linked List
void push(int data) {
Node * temp = new Node(data);
temp -> next = head;
head = temp;
}
};
//Driver Function
int main() {
LinkedList listl;
int n,k;
cout << "Enter the number of nodes in linked list: ";
cin >> n;
cout << "Enter the nodes: ";
for(int i=1;i<=n;i++){
cin >> k;
listl.push(k);
}
cout << "Given linked list\n";
listl.print();
listl.reverse();
cout << "\nReversed Linked list \n";
listl.print();
return 0;
}