基于数组实现Java 自定义Stack栈类及应用
栈是存放对象的一种特殊容器,在插入与删除对象时,这种结构遵循后进先出( Last-in-first-out,LIFO)的原则。java本身是有自带Stack类包,为了达到学习目的已经更好深入了解stack栈,自己动手自建java stack类是个很好的学习开始:
自建Java Stack 类
Stack 类:
package com.stack; import java.util.ArrayList;
import java.util.Arrays; /**
* Stack Class
* @author ganyee
*
*/
public class Stack {
//Define capacity constant:CAPACITY
private static final int CAPACITY = 1024;
//Define capacity
private static int capacity;
//Define the top position of stack
//top = -1 meaning that the stack empty
private static int top = -1;
//Basic Object class array
Object[] array;
//Initialize the capacity of stack
public Stack() {
this.capacity = CAPACITY;
array = new Object[capacity];
} //Get the size of stack
public int getSize(){
if(isEmpty()){
return 0;
}else{
return top + 1;
}
} //Get whether stack is empty
public boolean isEmpty(){
return (top < 0);
} //Get the top element of stack
public Object top() throws ExceptionStackEmpty{ if(isEmpty()){
throw new ExceptionStackEmpty("Stack is empty");
}
return array[top]; } //Push element to stack
public void push(Object element) throws ExceptionStackFull{
if(getSize()== CAPACITY){
throw new ExceptionStackFull("Stack is full");
}
array[++ top] = element;
} //Pop element from stack
public Object pop() throws ExceptionStackEmpty{
if(isEmpty()){
throw new ExceptionStackEmpty("Stack is empty");
}
return array[top --];
} //Get the all elements of stack
public String getAllElements() throws ExceptionStackEmpty{
String[] arr = new String[top + 1];
if(!isEmpty()){
for(int i = 0;i < getSize();i ++){
arr[i] = (String)array[i];
}
}
return Arrays.toString(arr);
}
}
自定义ExceptionStackEmpty异常类
package com.stack;
public class ExceptionStackEmpty extends Exception {
//Constructor
public ExceptionStackEmpty(){
}
//Define myself exception construct with parameters
public ExceptionStackEmpty(String string){
super(string);
}
}
自定义ExceptionStackFull异常类
package com.stack;
public class ExceptionStackFull extends Exception {
//Constructor
public ExceptionStackFull(){
}
//Define myself exception construct with parameters
public ExceptionStackFull(String string){
super(string);
}
}
测试类:
package com.stack;
public class StackTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack stack= new Stack();
System.out.println(stack.getSize());
System.out.println(stack.isEmpty());
try {
stack.push(8);
stack.push(3);
stack.push(4);
stack.push(7);
stack.push(1);
stack.push(8);
stack.push(3);
stack.push(4);
stack.push(7);
stack.push(1);
System.out.println(stack.getSize());
System.out.println(stack.top());
System.out.println(stack.getAllElements());
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());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
} catch (ExceptionStackFull e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ExceptionStackEmpty e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
测试结果:
0
true
10
1
[8, 3, 4, 7, 1, 8, 3, 4, 7, 1]
1
7
4
3
8
1
7
4
3
8
栈的应用:符号匹配
下面,我们将借助一个栈结构 S,通过对算术表达式自左向右的一遍扫描,检查其中的括号是否匹配。
假设算术表达式为 X = “x0x1x2…xn-1”,其中 xi 可以是括号、常数、变量名或者算术运算符。我们依次检查 X 中的各个符号,非括号的符号都可以忽略。若遇到左括号,则将其压入栈 S 中;若遇到右括号,则将栈顶符号弹出并与该右括号对比。如果发现某对括号不匹配,或者遇到右括号时栈为空,或者整个表达式扫描过后栈非空,都可以断定括号不匹配。
在按照以上规则扫描完所有字符后,若栈为空,则说明括号是匹配的。如果按照前面对栈的实现,每一 push()和 pop()操作都只需常数时间,因此对于长度为 n 的算术表达式,上述算法需要运行 O(n)的时间。
该算法的伪代码描述如 算法二.1 所示:

package com.stack;
public class MatchClass {
public static boolean Match(String str) throws ExceptionStackFull, ExceptionStackEmpty{
Stack stack = new Stack();
str = str.replaceAll(" ","");
char s;
for(int i = 0;i < str.length();i ++){
if(str.charAt(i) == '(' || str.charAt(i) == '{' || str.charAt(i) == '[')
stack.push(str.charAt(i));
else{
if(stack.isEmpty())
return false;
else{
s = str.charAt(i);
switch(s){
case ')':
if((Character)stack.pop() != '(')
return false;
break;
case '}':
if((Character)stack.pop() != '{')
return false;
break;
case ']':
if((Character)stack.pop() != '[')
return false;
break;
}
}
}
}
if(stack.isEmpty()){
return true;
}else{
return false;
}
}
}
package com.stack;
public class ParentMatch {
public static void main(String[] args) {
MatchClass match = new MatchClass();
//String str = "()({})"; //Match
//String str = "()({}) {([()[]])}";//Match
//String str = "([]{)";//Not match
//String str = ")([()] {}";//Not match
String str = "([())]{}";//Not match
try {
if(!match.Match(str)){
System.out.println(str + ": Not Macth");
}else{
System.out.println(str + ": Macth");
}
} catch (ExceptionStackFull e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExceptionStackEmpty e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
测试结果:
()({}): Macth
()({}) {([()[]])}: Macth
([]{): Not Macth
)([()] {}: Not Macth
([())]{}: Not Macth
基于数组实现Java 自定义Stack栈类及应用的更多相关文章
- java集合类——Stack栈类与Queue队列
Stack继承Vector类,它通过五个操作对类 Vector 进行了扩展. 栈是 后进先出的. 栈提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法.测试堆栈是否为空的 em ...
- 如何给女朋友讲明白:Java 中 Stack(栈) 与 Heap(堆)
背景 Java 中 Stack(栈) 与 Heap(堆) 是面试中被经常问到的一个话题. 有没有对 Java 中 Stack(栈) 与 Heap(堆) 烂熟于心的童鞋,请举手!!!(怎么没人举手-) ...
- 用 LinkedList 实现一个 java.util.Stack 栈
用 LinkedList 实现一个 java.util.Stack 栈 import java.util.LinkedList; public class Stack<E> { priva ...
- Java数据类型Stack栈、Queue队列、数组队列和循环队列的比较
判断括号是否匹配:调用java本身 import java.util.Stack; public class Solution { public boolean isValid(String s){ ...
- java.util.Stack(栈)的简单使用
import java.util.Stack; import org.junit.Before; import org.junit.Test; /** * Stack(栈)继承了Vector类,底层实 ...
- Stack栈类与、Queue队列与线性表的区别和联系
栈和队列都属于特殊的线性表 一.定义 1.线性表(linear list): 是数据结构的一种,一个线性表是n个具有相同特性的数据元素的有限序列.数据元素是一个抽象的符号,其具体含义在不同的情 ...
- java 编程基础 Class对象 反射 :数组操作java.lang.reflect.Array类
java.lang.reflect包下还提供了Array类 java.lang.reflect包下还提供了Array类,Array对象可以代表所有的数组.程序可以通过使 Array 来动态地创建数组, ...
- Java自定义一个字典类(Dictionary)
标准Java库只包含Dictionary的一个变种,名为:Hashtable.(散列表) Java的散列表具有与AssocArray相同的接口(因为两者都是从Dictionary继承来的).但有一个方 ...
- 对于java自定义的工具类的提炼 注意事项
1.工具类的方法都用static修饰. 因为工具类一般不创建对象,直接类名.方法()使用 2.一些 定义的常亮需要 public static final 修饰. 3.一些与数据库的连接之类的设定 , ...
随机推荐
- Maven学习(十八)-----Maven依赖管理
其中一个Maven的核心特征是依赖管理.管理依赖关系变得困难的任务一旦我们处理多模块项目(包含数百个模块/子项目). Maven提供了一个高程度的控制来管理这样的场景. 传递依赖发现 这是很通常情况下 ...
- PHP反序列化漏洞代码审计—学习资料
1.什么是序列化 A.PHP网站的定义: 所有php里面的值都可以使用函数serialize()来返回一个包含字节流的字符串来表示.unserialize()函数能够重新把字符串变回php原来的值. ...
- 百度云 win10 125%界面模糊 解决
右击图标 ->兼容性->更改高DPI设置 -> 替代高DPI缩放行为.打√
- python程序设计——面向对象程序设计:继承
继承是为代码复用和设计复用而设计的 在继承关系中,已有的.设计好的类称为父类或基类,新设计的类为子类或派生类 派生类可以继承父类的公有成员,但不能继承其私有成员 如果需要在派生类中调用基类的方法,可以 ...
- 高可用Kubernetes集群-9. 部署kubelet
十一.部署kubelet 接下来两个章节是部署Kube-Node相关的服务,包含:kubelet,kube-proxy. 1. TLS bootstrap用户授权 # kubelet采用TLS Boo ...
- 译 - 高可用的mesos计算框架设计
原文地址 http://mesos.apache.org/documentation/latest/high-availability-framework-guide/ 阅读建议:有写过或者看过Mes ...
- 【RL系列】蒙特卡罗方法——Soap Bubble
“肥皂泡”问题来源于Reinforcement Learning: An Introduction(2017). Exercise 5.2,大致的描述如下: 用一个铁丝首尾相连组成闭合曲线,浸入肥皂泡 ...
- K-means + PCA + T-SNE 实现高维数据的聚类与可视化
使用matlab完成高维数据的聚类与可视化 [idx,Centers]=kmeans(qy,) [COEFF,SCORE,latent] = pca(qy); SCORE = SCORE(:,:); ...
- 请教Amazon FBA里面Label Service, Stickerless, Commingled Inventory是什么意思?
Accept Label Service接受标签服务,选择了以后下面的操作中会有一个让您打印标签的流程,您就可以按照FBA流程提示进行每一步标签服务的操作. Accept Stickless, Com ...
- ORA-01747
java.sql.SQLException: ORA-01747: user.table.column, table.column 或列说明 语法中多了逗号 或者字段使用关键字