目录
前言
每天都能听到各个老师各种说栈和队列,什么栈帧啦,什么虚拟栈啦,那么它们到底是什么呢,现在就让我们进入栈的世界!
一、什么栈,什么是java虚拟机栈,什么是栈帧?
1.栈 是一种数据结构 特点 :先进后出 2.java虚拟机栈 :一段内存(局部变量...) 3.调用函数时会为函数开辟一块内存 叫做栈帧 (在虚拟机栈内)
二、栈的常用方法
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);//入栈
System.out.println(stack.pop());//出栈
System.out.println(stack.peek());//栈顶元素
System.out.println(stack.empty());//是否为空
System.out.println(stack.search(2));//寻找二下标的数
}
三、使用顺序表实现栈
package bag;
import java.util.Arrays;
/**
* Description:用顺序表实现栈 时间复杂度和空间复杂度都是O(1)
* 同样用单链表也可以实现 但是 需要头插法 而且尾结点不好出去
* 所以 应该 使用 双向链表 来实现 更加方便
*/
public class MyStack {
private int[] elem;
private int usedSize;
public MyStack(){
this.elem = new int[5];
}
public void push(int val){
if(isFull()){
this.elem = Arrays.copyOf(elem,2 * elem.length);
}
this.elem[this.usedSize] = val;
usedSize ++;
}
public boolean isFull(){
if(this.usedSize == this.elem.length){
return true;
}
return false;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空了!");
}
int a = this.elem[usedSize - 1];
this.usedSize--;
return a;
}
public boolean isEmpty(){
return this.usedSize == 0;
}
public int peek(){
if(isEmpty()){
throw new RuntimeException("栈空了!");
}
int a = this.elem[usedSize - 1];
return a;
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);//入栈
System.out.println(stack.pop());//出栈
System.out.println(stack.peek());//栈顶元素
System.out.println(stack.isEmpty());//是否为空
}
}
总结
以上就是所有内容了,一般牵扯到顺序关系的,基本和栈是离不开的,所以对于栈一定要学懂哦!