forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Linked List.cpp
83 lines (63 loc) · 1.38 KB
/
Reverse Linked List.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
73
74
75
76
77
78
79
80
81
82
83
// C++ implementation of reversing a Linked list given its Head pointer
#include <bits/stdc++.h>
using namespace std;
class ListNode
{
public:
int val;
ListNode *next;
};
ListNode *reverseList(ListNode *head)
{
if (!head || !head->next)
return head;
ListNode *p1, *p2, *p3;
p1 = nullptr;
p2 = head;
p3 = head->next;
while (p3)
{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
return p2;
}
int main()
{
ListNode *head = new ListNode();
ListNode *node2 = new ListNode();
ListNode *node3 = new ListNode();
ListNode *node4 = new ListNode();
ListNode *node5 = new ListNode();
head->val = 1;
head->next = node2;
node2->val = 2;
node2->next = node3;
node3->val = 4;
node3->next = node4;
node4->val = 4;
node4->next = node5;
node5->val = 5;
node5->next = nullptr;
ListNode *temp = head;
cout << "Initial Linked List: \n";
while (temp != nullptr)
{
cout << temp->val << "->";
temp = temp->next;
}
cout << "NULL";
head = reverseList(head);
temp = head;
cout << "\n\nReversed Linked List: \n";
while (temp != nullptr)
{
cout << temp->val << "->";
temp = temp->next;
}
cout << "NULL";
}
// This code is contributed by Omkar Jahagirdar (Github: omkar3602)