What is Stack in Data Structure ?

  • A stack is a container of objects that are performed based on last-in first-out (LIFO) principle.
  • A stack is a limited access data structure-elements can be added and removed from the stack only at the top. A stack is a recursive data structure.
  • The structural definition of a Stack is either empty or it consists of a top and the rest.
  • There are two basic operations performed in a Stack they are:
    • Push()
    • Pop()
    • Push()-push function is used to add or insert new item into the stack.
POP Operation
    • Pop()-pop function is used to delete or remove an item from the stack.
 Push Operation
  • When a stack is completely full, it is said to be Overflow state and if stack is completely empty, it is said to be Underflow state.
  • Stack allows operations at one end only.

Other operations used in Stack

  • Peek()-The peek() function gets the top element of the stack, without deleting it.
  • isEmpty() -The isEmpty() function checks whether the stack is empty or not.
  • isFull()-The isFull() function is used to check whether the stack is full or not.

Features of stacks

  • Dynamic data structures
  • Do not have a fixed size
  • Do not consume a fixed amount of memory
  • Size of stack changes with each push() and pop() operation. Each push() and pop() operation increases and decreases the size of the stack by 1, respectively.

Implementation of Stack

 Stack in Data Structure

Sample Code

import java.io.*;


/* Java program to implement basic stack
operations */
class Stack
{
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int b)
{
if (top >= (MAX-1))
{
System.out.println("Stack Overflow");
return false;
}
else
{
a[++top] = b;
System.out.println(b + " pushed into the stack");
return true;
}
}

int pop()
{
if (top < 0)
{
System.out.println("Stack Underflow");
return 0;
}
else
{
int b = a[top--];
return b;
}
}
}

// Driver code
class Main
{
public static void main(String args[])
{
Stack s1 = new Stack();
s1.push(80);
s1.push(75);
s1.push(90);
System.out.println(s1.pop() + " Popped from the stack");
}
}

Output

80 pushed into the stack
75 pushed into the stack
90 pushed into the stack
80 Popped from the stack

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,