# Please correct my below code - Reverse a single linked list

{

``````/*using temp below to traverse to end of linked list

struct Node *temp=NULL,*rev=NULL,*prev;
return rev;
{
if(rev==NULL)
{
while(temp->next)
{
prev=temp;
temp=temp->next;
}
rev=temp;
prev->next=NULL;
}
else
{
{
while(temp->next)
{
prev=temp;
temp=temp->next;
}
prev->next=NULL;
rev->next=temp;
}
}
}
return rev;
``````

}

My solution For This Problem

I think you start out by breaking the list near the end, and then setting a lot of links to NULL, and maybe end up with just two items? … since `rev` never moves after the first loop takes it to the end of the original list.

Here’s a Python example of reversing a linked list. The basic idea is that you have two extra pointers, here called `mid` and `fore`, plus the root pointer moving (behind them) through the list. After the process, `root` is pointing at the other end and all the list pointers are reversed.

``````
if root:
while mid:
root = mid
mid = fore

``````

it seems your solution uses two pointers and that’s where the problem is.

You can use three pointers: previousNode,currentNode, and nextNode.

The logic for this would be:

• Have three nodes i.e previousNode,currentNode and nextNode.
• When currentNode is starting node, then previousNode will be null
• AssigncurrentNode.next to previousNode to reverse the link.
• In each iteration move currentNode and previousNode by 1 node.

Here is the code:

``````public static Node reverseLinkedList(Node currentNode)
{
// For first node, previousNode will be null
Node previousNode=null;
Node nextNode;
while(currentNode!=null)
{
nextNode=currentNode.next;