-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathreversingLL.cpp
More file actions
47 lines (38 loc) · 850 Bytes
/
reversingLL.cpp
File metadata and controls
47 lines (38 loc) · 850 Bytes
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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
Node* reverseList(Node* head) {
Node* prev = nullptr;
Node* curr = head;
Node* next = nullptr;
while (curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void printList(Node* head) {
while (head != nullptr) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main() {
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: ";
printList(head);
head = reverseList(head);
cout << "Reversed list: ";
printList(head);
return 0;
}