Archive for Linked Lists

Deleting the entire linked list

This is another common interview question. The interviewer wants to see how you tackle the problem and maintain pointers to correctly de allocate all the memory reserved by the linked list.

Suppose you start with the head element and traverse the list and delete elements as you move along…but wait a minute! Do you advance the pointer first or delete the pointer first? Suppose you advance the pointer than how would you delete the previous node? And if you delete the node than you can’t advance as your node contains the address of the next element.  So to perform this function we would need to maintain two pointers one which would hold the current node and one which would hold the next node in the linked list. Here is a sample code in C++

Void Delete (Node ** head)
{

Node* temp = *head;
while (temp) {

Node * temp1 = temp->next;
delete temp;
temp = temp1;
}

*head = NULL;

}

Updated courtesy supergokhan

 

Advertisements

Comments (2)

Detecting a cycle in a linked List (Floyd’s Cycle Detection)

OK here is another very interesting interview problem which I wanted to discuss today. The problem at hand is that you are given a singly linked list and (unfortunately) it contains a cycle i.e. some node points back to an earlier node in the linked list. Your task being a software engineer is to detect if  the linked list contains a cycle.

My initial brainstorming gave me an idea that I should traverse the list and mark nodes on my way so if I reach a node that has already been marked Hurrah !! Got ya !

Lets see how this approach works. So now I need to maintain a status for every node so I updated my Node Structure as follows

Struct Node {
int data;
Node * link;
bool status;
}

Firstly I would have to initialize all nodes with status value equal to “false”

Node * temp = head;
while (temp) {
temp->status = false;
temp = temp->link;

}

Having done that now my job is very simple. I can detect the cycle as follows:

Node * current = head;
bool isCycle = false;

while (current){

if(current->status ==true){
isCycle = true;

}

current->status = true;
current=current->next;

}

The approach seems to be fine but it required us to change our original Node data structure. Supposing the interviewer wants you to come up with a solution that doesn’t change the underlying data structure than you need to figure out some other way. Let’s look at a different algorithm that achieves this.

Most of us would remember the rabbit and turtle story from our childhood where the rabbit was very quick and turtle was very slow during the race. Consider they were racing on a straight track and for sometime assume the rabbit didn’t become complacent and instead kept on running he would have reached the finish line much quicker than the turtle, however consider they were racing in a circular field and there was no finish line the rabbit would have moved ahead quickly and eventually would have crossed the turtle again after some time. Can we use this story for our help? Yes we surely can ! this algorithm is a classical example of Floyd’s Cycle Detection Algorithm or also known as Tortoise and Hare Algorithm. So if we have a cycle in our linked list than some where along the traversal the faster pointer (Hare) would meet the slower pointer (turtle) indicating we have a cycle , else the hare would reach the end of the linked list if there is no cycle. Let’s see how we can code this.

//Hare moves twice the speed of the Turtle so if we have a cycle eventually Hare would meet the turtle again.

bool isCycle(Node *head) {

Node * turtle, * Hare;

turtle=Hare=head;

while (Hare){

if(Hare>link ==turtle->link){

return true;

}

turtle = turtle->link;
Hare= Hare->link->link;

}

return false;

}

Comments (1)

mth from the last element of a singly linked list

Write a program to find the mth from the last element of a singly linked list

Singly Linked List

So for the linked list shown m= 0 would return the node with information field 1203 (tail element) and m = 1 would return node with information field 1202.

Solution:

This is a very common interview question. Let’s look at a very simple solution.

  1. Traverse the list and count the number of nodes.
  2. Calculate the offset of the mth from last element from the start using  offset = (length – m)
  3. Traverse the linked list again (for int i=1 ; i <=offset; i++) and return the current node.

However there must be a better way of approaching this instead of using loops to traverse the list twice.

Another solution can be as follows:

  1. Initialize two pointers p and q both pointing to the head of the linked list.
  2. Now let’s make the distance between p and q equals to m by incrementing the q pointed m times.
  3. Now check if q-> next == NULL (means we have reached the end of the linked list and p is at m positions from the last element so we return node pointed by p) else increment both points p = p-> next and q = q-> next and repeat step 3 again.

Rough implementation in C++ would be as follows:

Node * mthfromLast(Node * head, int m){

if(head==NULL|| m < 0)
{   return NULL;
}

Node * p, *q = head;

for (int i = 0 ; i < m; i++){
if(q->next == NULL)

{ return NULL;
}

q = q-> next;
}
while(q->next!= NULL) {

p = p-> next;

q = q-> next;

}
return p;
}

Singly Linked List Image was taken from : http://www.tech-faq.com/images/singly-linked-list_clip_image002.jpg

Leave a Comment