Type Here to Get Search Results !

Stack in java Using Array, ArrayList and LinkedList with example.

0

 Stack in java using array, arraylist and linkedlist with example.


In Java, a stack is a data structure that follows the Last-In-First-Out (LIFO) principle, where the last element added to the stack is the first one to be removed. The stack data structure can be implemented using an array or a linked list.

To create a stack in Java, you can use the Stack class, which is part of the java.util package. Here's an example:

import java.util.Stack;

public class StackExample {
   public static void main(String[] args) {
      Stack<Integer> stack = new Stack<Integer>();

      // Pushing elements onto the stack
      stack.push(10);
      stack.push(20);
      stack.push(30);

      // Popping elements from the stack
      while (!stack.empty()) {
         System.out.println(stack.pop());
      }
   }
}

In this example, we first create a Stack object called stack using the Stack<Integer> syntax, which indicates that it will contain elements of type Integer.

We then push three elements onto the stack using the push() method, which adds the elements to the top of the stack.

Next, we use a while loop to remove elements from the stack using the pop() method. This method removes and returns the top element of the stack. The loop continues until the stack is empty, which is determined using the empty() method.

When we run this program, the output will be:

30
20
10

This is because we added the elements 10, 20, and 30 to the stack in that order, but when we popped them off the stack, they came off in reverse order (30 first, then 20, then 10). This is because the stack follows the LIFO principle.


Here's an example of implementing a stack in Java using an array:

public class Stack {
    private int[] data;
    private int top;

    public Stack(int capacity) {
        data = new int[capacity];
        top = -1;
    }

    public void push(int value) {
        if (top == data.length - 1) {
            throw new StackOverflowError();
        }
        data[++top] = value;
    }

    public int pop() {
        if (top == -1) {
            throw new EmptyStackException();
        }
        return data[top--];
    }

    public int peek() {
        if (top == -1) {
            throw new EmptyStackException();
        }
        return data[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == data.length - 1;
    }
}


In this example, we have implemented the Stack class using an array. The class has a constructor that takes a capacity parameter and initializes an empty array with the given capacity. The push() method adds a new element to the top of the stack, and the pop() method removes and returns the top element. The peek() method returns the top element without removing it. The isEmpty() method returns true if the stack is empty, and the isFull() method returns true if the stack is full.

Here's an example of how to use the Stack class:


Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // Output: 3
System.out.println(stack.peek()); // Output: 2
System.out.println(stack.isEmpty()); // Output: false
System.out.println(stack.isFull()); // Output: false
stack.push(4);
stack.push(5);
System.out.println(stack.isFull()); // Output: true
stack.push(6); // Throws StackOverflowError

In this example, we create a stack with a capacity of 5 and push three elements to the stack. We then print the result of calling pop(), which removes and returns the top element of the stack, and peek(), which returns the top element without removing it. We also print the result of calling isEmpty() and isFull(), which return true or false depending on whether the stack is empty or full, respectively. Finally, we try to push a sixth element to the stack, which throws a StackOverflowError since the stack is already full.

Here's an example of how to implement a stack in Java using the built-in Stack class:

import java.util.Stack;

public class MyStack {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        // Adding elements to the stack
        stack.push(10);
        stack.push(20);
        stack.push(30);

        // Removing elements from the stack
        int top = stack.pop();
        System.out.println("Removed element: " + top);

        // Retrieving the top element without removing it
        int peek = stack.peek();
        System.out.println("Top element: " + peek);

        // Checking if the stack is empty
        boolean isEmpty = stack.isEmpty();
        System.out.println("Is the stack empty? " + isEmpty);
    }
}

Output :-

Removed element: 30
Top element: 20
Is the stack empty? false

In the above example, we first create a new Stack object using the Stack class provided by Java. We then add three elements to the stack using the push() method, which adds the element to the top of the stack.

We then remove an element from the top of the stack using the pop() method, which returns the element that was removed. We also retrieve the top element of the stack without removing it using the peek() method.

Finally, we check if the stack is empty using the isEmpty() method, which returns a boolean value indicating whether the stack is empty or not.

 Another Example of how to use the stack in Java:

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        // Pushing elements onto the stack
        stack.push(1);
        stack.push(2);
        stack.push(3);

        // Popping elements from the stack
        int element1 = stack.pop(); // 3
        int element2 = stack.pop(); // 2

        System.out.println("Element 1: " + element1);
        System.out.println("Element 2: " + element2);
    }
}


In this example, we first import the Stack class from the java.util package. We then create a new Stack object called stack to store integer elements.

We use the push() method to add elements 1, 2, and 3 to the stack. We then use the pop() method to remove the top two elements from the stack, storing them in element1 and element2.

Finally, we print out the values of element1 and element2, which should be 3 and 2, respectively. Note that the last element pushed onto the stack (element 1) is the first to be popped off the stack.

Here's an example of how to implement a stack using a linked list in Java:

public class Stack<T> {
    private Node<T> head;
    
    private static class Node<T> {
        private T data;
        private Node<T> next;
        
        private Node(T data) {
            this.data = data;
            this.next = null;
        }
    }
    
    public void push(T data) {
        Node<T> newNode = new Node<>(data);
        newNode.next = head;
        head = newNode;
    }
    
    public T pop() {
        if (head == null) {
            throw new EmptyStackException();
        }
        T data = head.data;
        head = head.next;
        return data;
    }
    
    public T peek() {
        if (head == null) {
            throw new EmptyStackException();
        }
        return head.data;
    }
    
    public boolean isEmpty() {
        return head == null;
    }
}

In this example, we define a Stack class that takes a type parameter T to represent the type of elements that will be stored in the stack. The Stack class has a private inner class Node that represents a node in the linked list. Each Node contains a data field to store the element and a next field to point to the next node in the list.

The Stack class has four methods:

push: Adds an element to the top of the stack by creating a new Node with the element and setting it as the new head of the linked list.
pop: Removes and returns the element at the top of the stack by setting the next node as the new head of the linked list.
peek: Returns the element at the top of the stack without removing it.
isEmpty: Returns true if the stack is empty.

Here is an example of how to implement a stack using the ArrayList class in Java:

import java.util.ArrayList;

public class StackExample {
   private ArrayList<Integer> stack;

   public StackExample() {
      stack = new ArrayList<Integer>();
   }

   public void push(int item) {
      stack.add(item);
   }

   public int pop() {
      int item = stack.get(stack.size()-1);
      stack.remove(stack.size()-1);
      return item;
   }

   public int peek() {
      return stack.get(stack.size()-1);
   }

   public boolean isEmpty() {
      return stack.isEmpty();
   }

   public static void main(String[] args) {
      StackExample myStack = new StackExample();
      myStack.push(10);
      myStack.push(20);
      myStack.push(30);

      System.out.println("Stack: " + myStack.stack);
      System.out.println("Peek: " + myStack.peek());
      System.out.println("Pop: " + myStack.pop());
      System.out.println("Stack: " + myStack.stack);
      System.out.println("Is Empty: " + myStack.isEmpty());
   }
}


In this example, the StackExample class uses an ArrayList to implement the stack. The push() method adds an item to the end of the ArrayList, the pop() method removes and returns the last item added, the peek() method returns the last item added without removing it, and the isEmpty() method checks whether the stack is empty.

Post a Comment

0 Comments