Stack has a provision of Last-In-First-Out (LIFO) mechanism for its elements - Data Structure

Q.  Which linear structure has a provision of Last-In-First-Out (LIFO) mechanism for its elements?
- Published on 19 Oct 15

a. Stack
b. Queue
c. Both a & b
d. None of the above

ANSWER: Stack
 

    Discussion

  • Nirja Shah   -Posted on 16 Nov 15
    Stack works on last in first out policy. It is a linear data structure.
    Consider a Example:
    class Stack
    {
        int top,size,i,item;
        int *stk;
      public:
       Stack()
      {
        top=-1;
        cout<<"Enter the size of stack";
        cin>>size;
        stk=new int[size];
      }
       void push()
      {
        if(top==size-1)
       {
         cout<<"stack is Full";
       }
    else
       {
         cout<<"Enter the "<<size<<" item\t\n";
         for(i=0;i<size;i++)
       {
         cin>>item;
         top++;
         stk[top]=item;
        }
       }
      }
    void pop()
    {
      if(top==-1)
      {
       cout<<"stack is empty";
      }
    else
      {
        cout<<"The deleted item is ::\t"<<stk[top]<<endl;
        top--;
      }
    }
    void display()
    {
       if(top==-1)
      {
        cout<<"stack is empty\n";
      }
    else
      {
        for(i=top;i>=0;i--)
      {
        cout<<stk[i]<<"\t\t";
     }
       }
      }
    };

    int main()
      {
        Stack obj;
        int choice;
        do
      {
        cout<<"Enter 1. for Push\n";
        cout<<"Enter 2. for Pop\n";
        cout<<"Enter 3. for showItem\n";
        cout<<"Enter 4. for Exit\n";
        cout<<"Enter you choice\n";
        cin>>choice;
       switch(choice)
      {
        case 1:
         obj.push();
         break;
        case 2:
         obj.pop();
         break;
        case 3:
         obj.display();
         break;
        case 4:
         break;

      }
    }
        while(choice<4);
        return 0;
    }

Post your comment / Share knowledge


Enter the code shown above:
 
(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)