Stack Stracture

Stack definition

stack是限定僅在表尾進行插入和刪除操作的線性表

或者

stack是限定在只能在棧頂進行插入和刪除操作的線性表

Stack Features

Last in First Out

Underlying principle inside the stack

stack是一個有順序的線性表,既然是線性表,底層是數組,

Because stack是Last in first out. 因此數組的index是0最適合做棧底, 因為變化最小

Source code of the Stack


Stack class Diagram

class Stack<E> extends Vector<E>

Stack Method

Implement stack structure with Java

package com.coffeland.test;    public class Stack  {      int Max = 5;      int top;      Object[] arr = new Object[5];        Stack(int maxSize)      {          this.Max = maxSize;          top = -1;      }        boolean push(int val)      {          // can not push the element into stack if the          if (top >= (Max-1))              return false;          else          {              top = top +1;              arr[top] = val;              System.out.println(val + " pushed into stack");              return true;          }      }        Object pop()      {          if(top < 0)              return -1;          else          {              arr[top--] = null;              return peek();          }      }        Object peek()      {          return arr[top];      }        void printArr()      {          for(Object elem : arr)          {              System.out.print (elem + " ");          }          System.out.println("-------------------------");      }        public static void main(String[] args) {          Stack s = new Stack(5);          s.push(10);          s.push(20);          s.push(30);          s.printArr();          s.pop();          s.printArr();      }  }  

output:

20 pushed into stack  30 pushed into stack  10 20 30 null null -------------------------  top = 1  10 20 null null null -------------------------    Process finished with exit code 0

Tags: