Introduction to stacks

* The Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

*The LIFO order says that the element which is inserted at the last in the Stack will be the first one to be removed. In LIFO order insertion takes place at the rear end of the stack and deletion occurs at the front of the stack.

*The FILO order says that the element which is inserted at the first in the Stack will be the last one to be removed. In FILO order insertion takes place at the rear end of the stack and deletion occurs at the front of the stack.


Mainly the following three basic operations are performed in the stack:

=>Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.

=>Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.

=>Peek or Top: Returns top element of stack.

=>isEmpty: Returns true if stack is empty, else false.


       


It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc .A real-world stack allows operations at one end only. For example, we can place or remove a card or plate from the top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At any given time, we can only access the top element of a stack.


                                 Cards | Free Stock Photo | A deck of playing cards on a black ...


Time Complexities of operations on stack: The operations push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of these operations.

There are two ways to implement a stack Using array and Using linked list.

A Push operation involves a series of steps −

Step 1 − Checks if the stack is full.

Step 2 − If the stack is full, produces an error and exit.

Step 3 − If the stack is not full, increments top to point next empty space.

Step 4 − Adds data element to the stack location, where top is pointing.

Step 5 − Returns success.
             
                


A Pop operation may involve the following steps −

Step 1 − Checks if the stack is empty.

Step 2 − If the stack is empty, produces an error and exit.

Step 3 − If the stack is not empty, accesses the data element at which top is pointing.

Step 4 − Decreases the value of top by 1.

Step 5 − Returns success.

        



             implementing stacks using arrays:
c++:
/* C++ program to implement basic stack operations */

#include<bits/stdc++.h>

using namespace std;

#define MAX 1000

class Stack
{
    int top;
public:
    int a[MAX];    //Maximum size of Stack

    Stack()  { top = -1; }
    bool push(int x);
    int pop();
    bool isEmpty();
};

bool Stack::push(int x)
{
    if (top >= (MAX-1))
    {
        cout << "Stack Overflow";
        return false;
    }
    else
    {
        a[++top] = x;
        cout<<x <<" pushed into stack\n";
        return true;
    }
}

int Stack::pop()
{
    if (top < 0)
    {
        cout << "Stack Underflow";
        return 0;
    }
    else
    {
        int x = a[top--];
        return x;
    }
}

bool Stack::isEmpty()
{
    return (top < 0);
}

int main()
{
    class Stack s;
    s.push(10);
    s.push(20);
    s.push(30);

    cout<<s.pop() << " Popped from stack\n";

    return 0;
}
java:

/* 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 x)
    {
        if (top >= (MAX-1))
        {
            System.out.println("Stack Overflow");
            return false;
        }
        else
        {
            a[++top] = x;
            System.out.println(x + " pushed into stack");
            return true;
        }
    }

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

// Driver code
class Main
{
    public static void main(String args[])
    {
        Stack s = new Stack();
        s.push(17);
        s.push(56);
        s.push(90);
        System.out.println(s.pop() + " Popped from stack");
    }
}
output:
17 pushed into stack
56 pushed into stack
90 pushed into stack
90 popped from stack

Pros: Easy to implement. Memory is saved as pointers are not involved.
Cons: It is not dynamic. It doesn’t grow and shrink depending on needs at runtime.


Implementing Stack using Linked List:
c++:
// C++ program for linked list implementation of stack

#include <bits/stdc++.h>

using namespace std;

// A structure to represent a stack
struct StackNode
{
    int data;
    struct StackNode* next;
};

// Utility function to create new stack node
struct StackNode* newNode(int data)
{
    struct StackNode* stackNode = new StackNode;
    stackNode->data = data;
    stackNode->next = NULL;
    return stackNode;
}

// Function to check if the Stack is empty
int isEmpty(struct StackNode *root)
{
    return !root;
}

// Function to push a new element onto Stack
void push(struct StackNode** root, int data)
{
    struct StackNode* stackNode = newNode(data);
    
    stackNode->next = *root;
    *root = stackNode;
    
    cout<<data<<" pushed to stack\n";
}

// Function to pop element from Stack
int pop(struct StackNode** root)
{
    if (isEmpty(*root))
        return INT_MIN;
        
    struct StackNode* temp = *root;
    *root = (*root)->next;
    
    int popped = temp->data;
    free(temp);

    return popped;
}

// Function to get the element present 
// at top of stack
int peek(struct StackNode* root)
{
    if (isEmpty(root))
        return INT_MIN;
        
    return root->data;
}

// Driver Code
int main()
{
    struct StackNode* root = NULL;

    push(&root, 10);
    push(&root, 20);
    push(&root, 30);

    printf("%d popped from stack\n", pop(&root));

    printf("Top element is %d\n", peek(root));

    return 0;
}

Java:
// Java Code for Linked List Implementation
// of Stacks

public class StackAsLinkedList {

    StackNode root;

    static class StackNode {
        int data;
        StackNode next;

        StackNode(int data) {
            this.data = data;
        }
    }
    
    public boolean isEmpty() {
        if (root == null) {
            return true;
        } else return false;
    }
    
    public void push(int data) {
        StackNode newNode = new StackNode(data);

        if (root == null) {
            root = newNode;
        } else {
            StackNode temp = root;
            root = newNode;
            newNode.next = temp;
        }
        System.out.println(data + " pushed to stack");
    }

    public int pop() {
        int popped = Integer.MIN_VALUE;
        if (root == null) {
            System.out.println("Stack is Empty");
        } else {
            popped = root.data;
            root = root.next;
        }
        return popped;
    }

    public int peek() {
        if (root == null) {
            System.out.println("Stack is empty");
            return Integer.MIN_VALUE;
        } else {
            return root.data;
        }
        
    }

    public static void main(String[] args) {
        
        StackAsLinkedList sll = new StackAsLinkedList();

        sll.push(10);
        sll.push(20);
        sll.push(30);

        System.out.println(sll.pop() + " popped from stack");
    
        System.out.println("Top element is " + sll.peek());
    }
}

output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
30 popped from stack
Top element is 20
Pros: The linked list implementation of stack can grow and shrink according to the needs at runtime.
Cons: Requires extra memory due to involvement of pointers.


Applications of stack:
Stacks can be used to check for the balancing of paranthesis in an expression.
Infix to Postfix/Prefix conversion.
Redo-undo features at many places like editors, photoshop.
Forward and backward feature in web browsers
And Many More




 

No comments

darkmode