Advertisement
flopana

Untitled

Dec 7th, 2022
1,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. public class Stack {
  2.     private Node top;
  3.     private final int maxSize;
  4.     private int size;
  5.  
  6.     static class Node {
  7.         Object data;
  8.         Node next;
  9.     }
  10.  
  11.     public Stack(int maxSize) {
  12.         this.top = null;
  13.         this.maxSize = maxSize;
  14.         this.size = 0;
  15.     }
  16.  
  17.     public void push(Object data) {
  18.         if (size == maxSize) {
  19.             throw new RuntimeException("Stack is full");
  20.         }
  21.         Node node = new Node();
  22.         node.data = data;
  23.         node.next = top;
  24.         top = node;
  25.         size++;
  26.     }
  27.  
  28.     public Object pop() {
  29.         if (size == 0) {
  30.             throw new RuntimeException("Stack is empty");
  31.         }
  32.         Object data = top.data;
  33.         top = top.next;
  34.         size--;
  35.         return data;
  36.     }
  37.  
  38.     public Object peek() {
  39.         if (size == 0) {
  40.             throw new RuntimeException("Stack is empty");
  41.         }
  42.         return top.data;
  43.     }
  44.  
  45.     public int size() {
  46.         return size;
  47.     }
  48.  
  49.     public boolean isEmpty() {
  50.         return size == 0;
  51.     }
  52.  
  53.     public boolean isFull() {
  54.         return size == maxSize;
  55.     }
  56.  
  57.     public void clear() {
  58.         top = null;
  59.         size = 0;
  60.     }
  61.  
  62.     public void print() {
  63.         Node node = top;
  64.         while (node != null) {
  65.             System.out.println(node.data);
  66.             node = node.next;
  67.         }
  68.     }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement