-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday5.cpp
68 lines (56 loc) · 1.38 KB
/
day5.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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node* prev;
Node(int d) {
data = d;
next = nullptr;
prev=nullptr;
}
};
Node* reverseList(Node* head) {
Node* current = head;
Node* temp = nullptr;
while (current != nullptr) {
// next = current->next;
// current->next = prev;
// prev = current;
// current = next;
temp=current->next;
current->next=current->prev;
current->prev=temp;
current =current->prev;
}
return current; // 'prev' points to the new head of the reversed list
}
// Function to display the linked list
void displayList(Node* head) {
Node* current = head;
while (current != nullptr) {
cout << current->data << " -> ";
current = current->next;
}
cout << "nullptr" << endl;
}
int main() {
// Create a sample linked list
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
cout << "Original List: ";
displayList(head);
// Reverse the linked list
head = reverseList(head);
cout << "Reversed List: ";
displayList(head);
// Clean up memory (deallocation)
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
return 0;
}