-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram-To-Reverse-LinkedList.cpp
More file actions
62 lines (47 loc) · 1.16 KB
/
Program-To-Reverse-LinkedList.cpp
File metadata and controls
62 lines (47 loc) · 1.16 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
#include <iostream.h>
#include <conio.h>
struct Node {
int data;
Node* next;
};
Node* reverseLinkedList(Node* head) {
Node* prev = NULL;
Node* current = head;
Node* nextNode = NULL;
while (current != NULL) {
nextNode = current->next; // Store the next node
current->next = prev; // Change the next of current node
// Move pointers one position ahead
prev = current;
current = nextNode;
}
return prev; // The new head after reversing
}
void display(Node* head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main() {
clrscr();
Node* head = NULL;
head = new Node;
head->data = 1;
Node* second = new Node;
second->data = 2;
Node* third = new Node;
third->data = 3;
head->next = second;
second->next = third;
third->next = NULL;
cout << "Original Linked List: ";
display(head);
head = reverseLinkedList(head);
cout << "Reversed Linked List: ";
display(head);
getch();
return 0;
}