Ferozeh dot Com
Expert advice on tech interviews !
about ferozeh

Ferozeh

Similar Questions


find 5th last in linkedlist


detect cycle in linkedlist


merge 2 sorted linkedlists

Question

Difficulty Level: 1

    • Write code to reverse a linked list That is the head becomes the tail and the tail becomes the head.

Solution

Explanation Quality:5

The idea is that you reverse the linked list in one pass and without using any extra space, that is you don't end up creating another linked list. We accomplish this by using a current pointer, a previous pointer and a temporary storage poiner. Here is the code:


*temporary = NULL;
*current = head;
*previous = NULL;

while(current){

 temporary = current->next; //storing the next element
 current->next = previous; //pointing backward
 previous = current; //updating previous
 current = temporary; // resetting current

}

temporary = head; //swapping head and tails
head = tail;
tail = temporary;

Note that I have intentionally left out the code for the case when the linked list consists of a single element. You MUST mention these corner cases to your interviewer !




Previous Next