• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Thursday, February 25, 2010

    Implement N stacks using constant sized array(space). Until the array is completely filled, I should be able to push elements to any one of the N stacks.(i.e.)Do not reserve space for the stacks. And I should also be able to pop elements from any stack.

    Sounds very tricky. The idea is :

    Keep an array S of N pointer, where each Si.top will point to the top of the corresponding stack. And one global pointer gptr, which points to the next free location in the array. Now follow the steps:

    Now implement Push(stackToPush) and pop(StackToPop) as follows :

    Push(x, Si) //pushing x in Stack Si.
    {
    if(gptr > sizeof(Arr))
    {
    // To Be Added -- explained below
    }
    Arr[gptr].data = x;
    Arr[gprt].prev = Si.top;
    Si.top = gptr;
    gptr++;
    }


    Pop(Si)
    {
    T data = Arr[Si.top].data; //T is data type
    Si.top = Arr[Si.top].prev;
    return data;
    }

    I would suggest that you try a very detailed dry-run with a little visual aid for this.

    0 comments:

    Post a Comment