AfterAcademy Tech
•
22 Jan 2020

Difficulty:Medium
Asked in: Microsoft, MakeMyTrip, Adobe, Amazon
Given a linked list pointed by a head node as input, your task is to reverse the linked list. After the reversal, The head data should become the last data element pointing to null. This should be done by de-linking the nodes and again linking it in reverse order.
For example:
Input: 2→3→4→5→6→7→NULL
Output: 7→6→5→4→3→2→NULL
Similarly
Input: 21→32→43→54→65→76→NULL
Output: 76→65→54→43→32→21→NULL
Possible follow-up questions to ask the interviewer:
Solution idea
The idea here is to de-link a node from its previous node and add the previous node in front of the current node. We will follow the same approach for all the node and finally our new reversed Linked List will be ready. This idea can be implemented in two ways →
Solution steps
head.next.next = head
head.next = NULL

Pseudo-Code
ListNode reverseList(ListNode head)
{
if(head == NULL || head.next == NULL)
return NULL
ListNode restReversedPart= reverseList(head.next)
head.next.next = head
head.next = NULL
return restReversedPart
}Complexity Analysis
Recurrence relation: T(n) = T(n-1) + O(1)
Time Complexity = O(n), where n is the length of the Linked List
Space Complexity = O(n), for recursion stack space. (Think!)
Solution steps
ListNode current = head
ListNode previous = NULL
ListNode nextNode = NULL
nextNode = current.next
current.next = previous
previous = current
current = nextNode
Pseudo-Code
ListNode reverseList(ListNode head)
{
if(head == NULL)
return NULL
ListNode current = head
ListNode previous = NULL
ListNode nextNode = NULL
while(current != NULL)
{
nextNode = current.next
current.next = previous
previous = current
current = nextNode
}
return previous
}
Complexity Analysis
Time Complexity = O(n), where n is the length of the Linked List
Space Complexity = O(1)
Critical ideas to think!
Happy Coding! Enjoy Algorithms!!
AfterAcademy Tech
In this blog, we will discuss the types of linked list and basic operations that can be performed on a linked list.

AfterAcademy Tech
This is an interview problem asked in companies like Amazon, Facebook and Microsoft. The problem is to reverse a linked list from position m to n and print the reversed linked list.

AfterAcademy Tech
Given a non-empty, singly linked list with head node head, write a program to return a middle node of linked list. If there are even nodes, then there would be two middle nodes, we need to print second middle element.

AfterAcademy Tech
Array and Linked List are the two most used data structures. It's really important to understand and compare the advantages and disadvantages of both array and linked list. In this blog, we will compare these two linear data structures. So let's get started.
