Stack Stracture
- 2020 年 3 月 5 日
- 笔记
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