Tuesday, December 13, 2011

Flatten a Linked List

Given a linked list structure where every node represents a linked list and 
contains two pointers of its type: 
(i) pointer to next node in the main list. 
(ii) pointer to a linked list where this node is head. 

From each node either we can go down or right.
Write a C function to flatten the list into a single linked list. 

Eg. 

If the given linked list is 
1 -- >5 -- >7 --> 10 
|       |      | 
2     6     8 
|       | 
3     9 



then convert it to 
1 - 2 - 3 - 4 - 5 - 6 - 9 - 7 - 8 -10

http://www.geeksforgeeks.org/flattening-a-linked-list/

Question 2:
How the solution will change if the list at down pointer can also point to another list with its down pointer as shown below


                           1 -- >5 -- >7 --> 10 
                            |       |      | 
             5 <--8<- -2     6     8 
                            |       | 
                            3     9 ->10->11
                             | 
                            4
http://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/
http://www.geeksforgeeks.org/flatten-a-multi-level-linked-list-set-2-depth-wise/

Strategy:
We will make down pointer of node with value 4 to point node with value 5 and proceed likewise.
During traversal we will use top->down as next of each node.

Code:

#include<stdio.h>

struct node {
int data;
struct node *fwd; //pointer to next node in the main list.
struct node *down; //pointer to a linked list where this node is head.
};


struct node *Flatten(struct node *head) 
{
struct node *temp = head, *fwd;
while (temp != NULL)
{
   fwd = temp->fwd;
   while (temp->down != NULL) 
   {
         temp = temp->down;
   }
   
temp->down = fwd;
temp->fwd = NULL;
temp = fwd;
}

return head;
}

int main() 
{
    
struct node
n12 = { 12, NULL, NULL },
n11 = { 11, NULL, &n12 },
n10 = { 10, NULL, &n11 },
n8 = { 8, NULL, NULL },
n7 = { 7, &n10, &n8 },
n9 = { 9, NULL, NULL },
n6 = { 6, NULL, &n9 },
n5 = { 5, &n7, &n6 },
n4 = { 4, NULL, NULL },
n3 = { 3, NULL, &n4 },
n2 = { 2, NULL, &n3 },
n1 = { 1, &n5, &n2 },

*result = Flatten(&n1);

while (result != NULL) {
printf("%d%s", result->data, result->down ? " - " : "");
result = result->down;
}
puts("");
getchar();
return 0;
}

3 comments:

  1. http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-linked-lists

    ReplyDelete
  2. http://geeksforgeeks.org/forum/topic/microsoft-interview-question-for-software-engineerdeveloper-fresher-about-linked-lists-15

    ReplyDelete
  3. http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-linked-lists-3

    ReplyDelete