数据结构本身和语言无关,为了方便理解本文使用java语言举例说明,介绍栈是什么?栈特性和栈使用场景
文章目录
- 数据结构-栈
- 一、栈是什么
- 二、java实现栈
- 1.栈实现类
- 2.测试
- 3.测试结果:
- 特性
- 优缺点
- 1.优点
- 1.缺点
- 应用场景
- 总结
一、栈是什么
栈(stack)是一种运算受限的线性表。只能在栈顶进行插入和删除操作的线性表。顶部称为栈顶,相对地,底部称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉返回该元素,然后使其相邻的元素成为新的栈顶元素。
二、java实现栈 1.栈实现类package com.luodea.datastructure;
public class Stack {
private Element top;
public void push(Object value){
if (top == null){
top = new Element(value);
}else{
Element previous = top;
top = new Element(value);
top.setPrevious(previous);
}
}
public Object pop(){
if (top ==null){
return null;
}
Element popElement = top;
if (popElement.getPrevious() ==null){
top = null;
return popElement.getElementValue();
}
top = top.getPrevious();
popElement.setPrevious(null);
return popElement.getElementValue();
}
public static class Element {
private Element previous;
private final Object elementValue;
public Element( Object elementValue) {
this.elementValue = elementValue;
}
public void setPrevious(Element previous) {
this.previous = previous;
}
public Element getPrevious() {
return previous;
}
public Object getElementValue() {
return elementValue;
}
}
}
2.测试
public static void main(String[] args) {
Stack stack = new Stack();
stack.push("value-1");
stack.push(2);
stack.push(new Integer(3) );
stack.push("value-4");
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
3.测试结果:
value-4
3
2
value-1
null
null
测试发现最先压栈的数据最后才弹出
特性优缺点 1.优点数据先入后出
1.缺点数据结构简单,操作效率非常高
应用场景数据结构简单,只能适用于特殊场景
在计算机底层的运算操作大部分采用该数据结构,如java执行一个方法就是将方法相关变量进行压栈然后通过指令出栈运算的过程。
总结
栈数据结构简单执行效率高,一般适合先进后出的应用场景。



