Advertisement
Guest User

Untitled

a guest
Apr 21st, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. package com.company;
  2.  
  3. public class Stack {
  4.     private Double[] _array; // inner array to store information
  5.     private int _top;
  6.  
  7.     public Stack() {
  8.         this(0);
  9.     }
  10.  
  11.     public Stack(int size) {
  12.         _array = new Double[size];
  13.         _top = -1; // initial index
  14.         // if we use this initial index then _top will show us exactly the last element
  15.     }
  16.  
  17.     private void resize() {
  18.         int capacity = ((_top+1) == 0) ? 4 : (_top) * 2; // ascending rule of array
  19.         Double[] array = new Double[capacity];
  20.         if (_top != -1) { // there are something to copy
  21.  
  22.             for (int i = 0; i < _top + 1; i++) { // manual array copy. O(n) complexity
  23.                 array[i] = _array[i];
  24.             }
  25.         }
  26.         _array = array; // new link for the array
  27.     }
  28.  
  29.     public void push(Double item) { // in worst case O(n) complexity because of resize
  30.         if (_top == -1 || this.isFull()) { // if the array is full
  31.             this.resize();
  32.         }
  33.  
  34.         _array[++_top] = item; // storing the new element at the top of array
  35.  
  36.     }
  37.  
  38.     public Double pop() { // returns last element and deletes it
  39.         if (!this.isEmpty())
  40.             return _array[_top--];
  41.         else
  42.             return null;
  43.     }
  44.  
  45.     public Double peek() {
  46.         return _array[_top];
  47.     } // view top element without deleting
  48.  
  49.     public int getCount() {
  50.         return _top + 1;
  51.     }
  52.  
  53.     public boolean isEmpty(){
  54.         return _top == -1;
  55.     }
  56.  
  57.     private boolean isFull(){
  58.         return _top == _array.length - 1;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement