-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse Linked List
37 lines (30 loc) · 982 Bytes
/
Reverse Linked List
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
#include <bits/stdc++.h>
/****************************************************************
Following is the class structure of the LinkedListNode class:
template <typename T>
class LinkedListNode
{
public:
T data;
LinkedListNode<T> *next;
LinkedListNode(T data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
LinkedListNode<int> *reverseLinkedList(LinkedListNode<int> *head)
{
LinkedListNode<int> *prev = nullptr;
LinkedListNode<int> *curr = head;
LinkedListNode<int> *next = nullptr;
while (curr != nullptr)
{
next = curr->next; // Store the next node
curr->next = prev; // Reverse the link
prev = curr; // Move prev to current node
curr = next; // Move current node to next node
}
return prev; // Return the new head of the reversed linked list
}