How to implement three stacks using a single array

后端 未结 17 773
情书的邮戳
情书的邮戳 2020-12-23 15:10

I came across this problem in an interview website. The problem asks for efficiently implement three stacks in a single array, such that no stack overflows until there is no

17条回答
  •  庸人自扰
    2020-12-23 15:54

    This code implements 3 stacks in single array. It takes care of empty spaces and fills the empty spaces in between the data.

    #include

    struct stacknode {
       int value;
       int prev;
    };

    struct stacknode stacklist[50];
    int top[3] = {-1, -1, -1};
    int freelist[50];
    int stackindex=0;
    int freeindex=-1;

    void push(int stackno, int value) {
       int index;
       if(freeindex >= 0) {
         index = freelist[freeindex];
         freeindex--;
       } else {
         index = stackindex;
         stackindex++;
       }
       stacklist[index].value = value;
       if(top[stackno-1] != -1) {
         stacklist[index].prev = top[stackno-1];
       } else {
         stacklist[index].prev = -1;
       }
       top[stackno-1] = index;
       printf("%d is pushed in stack %d at %d\n", value, stackno, index);
    }

    int pop(int stackno) {
       int index, value;
       if(top[stackno-1] == -1) {
         printf("No elements in the stack %d\n", value, stackno);
         return -1;
       }
       index = top[stackno-1];
       freeindex++;
       freelist[freeindex] = index;
       value = stacklist[index].value;
       top[stackno-1] = stacklist[index].prev;
       printf("%d is popped put from stack %d at %d\n", value, stackno, index);
       return value;
    }

    int main() {
       push(1,1);
       push(1,2);
       push(3,3);
       push(2,4);
       pop(3);
       pop(3);
       push(3,3);
       push(2,3);
    }

提交回复
热议问题