栈数据结构
1.定义:
一种基于先进后出(FILO)原则的数据结构。
2.图解:
3.栈数据结构的设计
4.代码实现(链表):
(1)Stack栈帧的属性与构造方法:
//头结点:
private Node head;
//元素个数:
private int length;
//构造方法:(栈数据结构的初始化)
public Stack_栈(){
head = new Node(null,null);
length = 0;
}
(2)结点内部类Node:
//结点内部类:
private class Node{
//数据域:
T item;
//指针域:
Node next;
//构造方法:
public Node(T item,Node next){
this.item = item;
this.next = next;
}
}
(3)功能方法:
<1>判断栈是否为空:
//获取栈是否为空方法:
public boolean isEmpty(){
return length == 0;
}
<2>获取栈中元素个数:
//获取栈中元素个数的元素:
public int getLength(){
return length;
}
<3>压栈:
//压栈:
public void push(T pushElement){
//创建出新结点:
Node newNode = new Node(pushElement,null);
//①将新结点的下一个改为原第一个结点;(初始为空时省略该步骤)
//②将头结点的下一个改为新结点;
if (!(isEmpty())){
newNode.next = head.next;
}
head.next = newNode;
//长度+1:
length++;
}
<4>弹栈:
//弹栈:
public T pop(){
//栈中无元素时,无需弹栈:
if (isEmpty()) return null;
//①获取被弹出的栈帧,以便返回值;
//②将头结点的下一个改为第二个结点;
T deleteElement = head.next.item;
head.next = head.next.next;
//长度-1:
length--;
return deleteElement;
}
5.栈数据结构的应用:
(1)逆波兰表达式(后缀表达式):
<1>.例子:
例:
==a+(b-c)*d ----> abc-d\*+==
==a*(b-c)+d ----> abc-*d+==
<2>.设计需求:
写出逆波兰表达式的算法函数;
<3>.思路分析:
①用数组储存逆波兰表达式,遍历该数组;
②遍历到数组将其压入栈中;遍历到运算符号则弹栈两下并储存弹出数据,再做相应的运算操作;
③得出结果输出返回即可;
<4>.代码实现:
A.测试方法:
public static void main(String[] args) {
String[] str = {"10","5","4","-","5","*","+"};
System.out.println(ReservePolishNotation(str));
}
B.求解逆波兰表达式方法:
//计算逆波兰表达式的函数:
public static int ReservePolishNotation(String[] str){
//创建出一个栈:
Stack_栈<Integer> stack = new Stack_栈 <>();
//遍历str数组:
for (int i = 0;i < str.length;i++){
Integer num1 = 0;
Integer num2 = 0;
Integer result = 0;
switch (str[i]){
case "+":
num1 = stack.pop();
num2 = stack.pop();
result = num1 + num2;
stack.push(result);
break;
case "-":
num1 = stack.pop();
num2 = stack.pop();
result = num2 - num1;
stack.push(result);
break;
case "*":
num1 = stack.pop();
num2 = stack.pop();
result = num1 * num2;
stack.push(result);
break;
case "/":
num1 = stack.pop();
num2 = stack.pop();
result = num2 / num1;
stack.push(result);
break;
default:
stack.push(Integer.parseInt(str[i]));
break;
}
}
int result = stack.pop();
return result;
}
C.测试结果:15(无问题)。
完!