Google interview question

Insert a node in to sorted circular linked list.

Interview Answers

Anonymous

31 Jan 2014

This is an easy yet tricky question. here's how I solved it -> it has three boundary conditions - 1) List is empty 2) Value of node is less than value of head 3) Value of node is greater than last node of the CLL. You need to see a special case, how will the code behave if you're trying to add a node which is already present in the CLL? Let's assume that we include the node even if it's a duplicate - here's how the code goes in C typedef struct node { int data; struct node *next; }; void addNode( node **head , node *p){ //since we may change the value of head, //hence **head, p is node to be added node *cur = *head; //initialize a temp node for traversing //handle boundary condition 1 if(*head == NULL){ *head = p; p->next = p; //point to itself since its a CLL return; } //handle the 2nd boundary condition if(p->data data){ //node should go before head node p->next = *head; while(cur->next != *head){ //place the cur pointer to end of CLL cur = cur->next; // in order to update the last element } cur->next = p; //last element points to new head *head = p; // old head points to new head return; } while(cur->next!=*head) { //iterate till last element of the CLL if(!(cur->data data && cur->next->data >= p->data)) //keep traversing until you find the right position cur = cur->next; } //handle the 3rd boundary condition if(cur->next == *head){ cur->next = p; p->next = *head; return; } //normal insertion at the appropriate place p->next = cur->next; cur->next = p; return; }

1

Anonymous

3 July 2014

In addition to SSB's response above, one should consider that there may be a loop in the list. At the very least, it is something to mention that you thought about in the interview.

1