stack是限定仅在表尾进行插入和删除操作的线性表
或者
stack是限定在只能在栈顶进行插入和删除操作的线性表
Last in First Out
stack是一个有顺序的线性表,既然是线性表,底层是数组,
Because stack是Last in first out. 因此数组的index是0最适合做栈底, 因为变化最小
class Stack<E> extends Vector<E>
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
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。