Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Sunday, August 6, 2017

Flattening a Linked List


Problem:



Logic:

Merge first two LL and get a merge list , now merge other lists with merged list iteratively.

Code :

class Node
{
int data;
Node next;
Node bottom;

Node(int d)
{
data = d;
next = null;
bottom = null;
}
}
class hackerranksolutionc
{
    Node merge(Node a,Node b)
    {
        if(a==null)
        return b;
        if(b==null)
        return a;
        Node data=null;
        if(a.data<b.data)
        {
            data=a;
            data.bottom=merge(a.bottom,b);
        }
        else
        {
            data=b;
            data.bottom=merge(a,b.bottom);
        }
        return data;
    }
    Node flatten(Node root)
    {
    if(root==null)
    return null;
    Node cur=root;
    Node nxt=cur.next;
    while(nxt!=null)
    {
        cur=merge(cur,nxt);
        nxt=nxt.next;
    }
    return cur;
    }
}

0 Comments:

Post a Comment

Stats