-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1.cpp
More file actions
56 lines (45 loc) · 1.07 KB
/
Q1.cpp
File metadata and controls
56 lines (45 loc) · 1.07 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
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseLinkedList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
ListNode* forward;
while (curr != NULL) {
forward = curr->next;
curr->next = prev;
prev = curr;
curr = forward;
}
head = prev;
return head;
}
void printList(ListNode* head) {
ListNode* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
int main() {
// Create a linked list with some random values
ListNode* head = new ListNode(1);
ListNode* t1 = new ListNode(2);
head->next = t1;
ListNode* t2 = new ListNode(3);
t1->next = t2;
ListNode* t3 = new ListNode(4);
t2->next = t3;
cout << "Original Linked List: ";
printList(head);
// Reverse the linked list
head = reverseLinkedList(head);
cout << "Reversed Linked List: ";
printList(head);
return 0;
}