In singly linked list, each node contains reference to next node. Address of previous node is not stored in any node, so reverse a singly linked list is a tricky question.
For start we will assign previous node as null and currentNode as head of linked list.Till we reach to the last node of list, first store next node in a temporary node and make current node’s next as previous node. Then for next iteration, current node become previous node and nextNode becomes CurrentNode.
public Node ReverseLinkedList(Node head)
if (head.next == null)
Console.WriteLine(" " + head.val);
Node preNode = null;
Node currentNode = head;
while (currentNode != null)
Node nextNode = currentNode.next;
currentNode.next = preNode;
preNode = currentNode;
currentNode = nextNode;
head = preNode;