基于数组实现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.一些与数据库的连接之类的设定 , ...
随机推荐
- Linux环境配置备忘
1.Ubuntu服务器版本装scipy 预装版本可能fortran包版本过旧或者不全,安装scipy之前需要更新环境. sudo apt-get install gfortran libopenbla ...
- Elasticsearch.Net 异常:[match] query doesn't support multiple fields, found [field] and [query]
用Elasticsearch.Net检索数据,报异常: )); ElasticLowLevelClient client = new ElasticLowLevelClient(settings); ...
- 如何选择合适的Qt5版本?
注意:这里讨论的是在不编译Qt源码的情况下,推荐下载的官方编译版本. 支持XP SP3以及之后的Windows版本:推荐 Qt5.6 或 Qt5.9,这两个版本是LTS版本(即长期支持版本),Bug较 ...
- python基础知识-04-字符串列表元组
python其他知识目录 内存,cpu,硬盘,解释器 实时翻译 编译器 :一次性翻译python2,3 除法,2不能得小数,3能得小数 1.字符串操作 1.1字符串操作startswith start ...
- ERROR [IM002] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序
在用c#生成应用程序的时候,读写dbf时,open方法出错 ERROR [IM002] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序 以前这个程序是用着好 ...
- scrum立会报告+燃尽图(第三周第三次)
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2286 项目地址:https://coding.net/u/wuyy694 ...
- 寻找bug
bug1:void不应有返回值. bug2:while(n--)没有条件终止循环. bug3:size和data没有定义 bug4:arr 是sz 在大于0的情况下创建的 一定部位bull 下面的 ...
- 软工1816 · Alpha冲刺(8/10)
团队信息 队名:爸爸饿了 组长博客:here 作业博客:here 组员1(组长):王彬 过去两天完成了哪些任务 推进前后端各个接口的整合 学习jQuery基本语法,为beta阶段的商铺页面做准备 接下 ...
- ASP.NET Core 中的 Razor 页面介绍
标题:ASP.NET Core 中的 Razor 页面介绍 地址:https://docs.microsoft.com/zh-cn/aspnet/core/razor-pages/index?view ...
- 第三章 ServerSpcket用法详解
构造ServerSocket ServerSocket的构造方法如下: ServerSocket() //Creates an unbound server socket. ServerSocket( ...