29
loading...
This website collects cookies to deliver better user experience
LinkedList
Data structure.head
of a singly linked list, reverse the list, and return the reversed list.💡 Give yourself at least 15-20 mins to figure out the solution :)
💁🏻♂️ Tip: You need to be good at pointer manipulations.
prev = null
, nex = null
, cur = head
. At every iteration cur
will point to the current node, prev
will point to its preceding node and nex will point to its succeeding node.cur's
next, take hold of its succeeding node )prev
for following iteration )cur
for following iteration )head = prev
( prev points to the first node of reversed linked list )head
//Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode *reverseList(ListNode *head)
{
ListNode *prev = nullptr;
ListNode *cur = head;
ListNode *next = nullptr;
//while cur is pointing to a node
while (cur)
{
//get access to the node ahead
next = cur->next;
//break the forward link
cur->next = prev;
//moving prev ahead
prev = cur;
//updating current node
cur = next;
}
//After the loop, prev will be pointed to the required node
head = prev;
return head;
}
💡 Can you think of a recursive solution? I will answer this in the next post.