Advertisement
makispaiktis

DCP43 - Implementing a stack

Oct 11th, 2020 (edited)
1,949
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class Stack {
  4.    
  5.     // Variables
  6.     public ArrayList <Double> stack;
  7.    
  8.     // Constructor
  9.     Stack(){
  10.         stack = new ArrayList <Double> ();
  11.     }
  12.     // Methods
  13.     //  Push
  14.     public void push(double val) {
  15.         stack.add(val);
  16.     }
  17.     // Pop
  18.     public double pop() {
  19.         if(stack.size() == 0) {
  20.             System.out.println("Error. It is not permitted to pop element from a stack with size = 0");
  21.             return -1000;
  22.         }
  23.         double value = stack.remove(stack.size()-1);               
  24.         return value;
  25.     }
  26.     // Max
  27.     public double max() {
  28.         if(stack.size() == 0) {
  29.             System.out.println("Error. I cannot find man element in a stack with size = 0");
  30.             return -1000;
  31.         }
  32.         double MAX = stack.get(0);
  33.         for(int i=1; i<stack.size(); i++) {
  34.             if(stack.get(i) > MAX) {
  35.                 MAX = stack.get(i);
  36.             }
  37.         }
  38.         return MAX;
  39.     }
  40.     // Show
  41.     public void show() {
  42.         System.out.println("******** STACK ********");
  43.         for(int i=0; i<stack.size(); i++) {
  44.             System.out.println(stack.get(i));
  45.         }
  46.         System.out.println();
  47.     }
  48.    
  49.     // MAIN FUNCTION
  50.     public static void main(String args[]) {
  51.         Stack STACK = new Stack();
  52.         STACK.push(1);
  53.         STACK.push(2);
  54.         STACK.push(3);
  55.         STACK.push(4);
  56.         double popped = STACK.pop();
  57.         System.out.println("Popped = " + popped);
  58.         STACK.show();
  59.         STACK.push(5);
  60.         STACK.push(8);
  61.         STACK.push(7);
  62.         STACK.push(6);
  63.         double MAX = STACK.max();
  64.         System.out.println("Max = " + MAX);
  65.         System.out.println();
  66.         STACK.show();
  67.     }
  68.    
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement