Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- public class Stack {
- private Double[] _array; // inner array to store information
- private int _top;
- public Stack() {
- this(0);
- }
- public Stack(int size) {
- _array = new Double[size];
- _top = -1; // initial index
- // if we use this initial index then _top will show us exactly the last element
- }
- private void resize() {
- int capacity = ((_top+1) == 0) ? 4 : (_top) * 2; // ascending rule of array
- Double[] array = new Double[capacity];
- if (_top != -1) { // there are something to copy
- for (int i = 0; i < _top + 1; i++) { // manual array copy. O(n) complexity
- array[i] = _array[i];
- }
- }
- _array = array; // new link for the array
- }
- public void push(Double item) { // in worst case O(n) complexity because of resize
- if (_top == -1 || this.isFull()) { // if the array is full
- this.resize();
- }
- _array[++_top] = item; // storing the new element at the top of array
- }
- public Double pop() { // returns last element and deletes it
- if (!this.isEmpty())
- return _array[_top--];
- else
- return null;
- }
- public Double peek() {
- return _array[_top];
- } // view top element without deleting
- public int getCount() {
- return _top + 1;
- }
- public boolean isEmpty(){
- return _top == -1;
- }
- private boolean isFull(){
- return _top == _array.length - 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement