栈是存放对象的一种特殊容器,在插入与删除对象时,这种结构遵循后进先出( 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栈类及应用的更多相关文章

  1. java集合类——Stack栈类与Queue队列

    Stack继承Vector类,它通过五个操作对类 Vector 进行了扩展. 栈是 后进先出的. 栈提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法.测试堆栈是否为空的 em ...

  2. 如何给女朋友讲明白:Java 中 Stack(栈) 与 Heap(堆)

    背景 Java 中 Stack(栈) 与 Heap(堆) 是面试中被经常问到的一个话题. 有没有对 Java 中 Stack(栈) 与 Heap(堆) 烂熟于心的童鞋,请举手!!!(怎么没人举手-) ...

  3. 用 LinkedList 实现一个 java.util.Stack 栈

    用 LinkedList 实现一个 java.util.Stack 栈 import java.util.LinkedList; public class Stack<E> { priva ...

  4. Java数据类型Stack栈、Queue队列、数组队列和循环队列的比较

    判断括号是否匹配:调用java本身 import java.util.Stack; public class Solution { public boolean isValid(String s){ ...

  5. java.util.Stack(栈)的简单使用

    import java.util.Stack; import org.junit.Before; import org.junit.Test; /** * Stack(栈)继承了Vector类,底层实 ...

  6. Stack栈类与、Queue队列与线性表的区别和联系

    栈和队列都属于特殊的线性表   一.定义   1.线性表(linear list): 是数据结构的一种,一个线性表是n个具有相同特性的数据元素的有限序列.数据元素是一个抽象的符号,其具体含义在不同的情 ...

  7. java 编程基础 Class对象 反射 :数组操作java.lang.reflect.Array类

    java.lang.reflect包下还提供了Array类 java.lang.reflect包下还提供了Array类,Array对象可以代表所有的数组.程序可以通过使 Array 来动态地创建数组, ...

  8. Java自定义一个字典类(Dictionary)

    标准Java库只包含Dictionary的一个变种,名为:Hashtable.(散列表) Java的散列表具有与AssocArray相同的接口(因为两者都是从Dictionary继承来的).但有一个方 ...

  9. 对于java自定义的工具类的提炼 注意事项

    1.工具类的方法都用static修饰. 因为工具类一般不创建对象,直接类名.方法()使用 2.一些 定义的常亮需要 public static final 修饰. 3.一些与数据库的连接之类的设定 , ...

随机推荐

  1. CC2541调试问题记录-第一篇

    1. 在网络环境过于复杂的地方,手机连接不上CC2541.2. 修改CC2541的设备名字. static uint8 scanRspData[] = { // complete name 0x0d, ...

  2. apache开启伪静态的方法 php篇

    打开apache的配置文件httpd.conf 找到 #LoadModule rewrite_module modules/mod_rewrite.so 把前面#去掉.没有则添加,但必选独占一行,使a ...

  3. equals和==方法比较(二)--Long中equals源码分析

    接上篇,分析equals方法在Long包装类中的重写,其他类及我们自定义的类,同样可以根据需要重新equals方法. equals方法定义 equals方法是Object类中的方法,java中所有的对 ...

  4. 华为云分布式缓存服务DCS与开源服务差异对比

    华为云分布式缓存DCS提供单机.主备.集群等丰富的实例类型,满足用户高读写性能及快速数据访问的业务诉求.支持丰富的实例管理操作,帮助用户省去运维烦恼.用户可以聚焦于业务逻辑本身,而无需过多考虑部署.监 ...

  5. 【python 3.6】笨办法取出列表中的字典的value

    #python 3.6 #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'BH8ANK' x = {'RegionSet': [{' ...

  6. 【Python 开发】Python目录

    目录: [Python开发]第一篇:计算机基础 [Python 开发]第二篇 :Python安装 [Python 开发]第三篇:python 实用小工具

  7. PReLU——Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification

    1. 摘要 在 \(ReLU\) 的基础上作者提出了 \(PReLU\),在几乎没有增加额外参数的前提下既可以提升模型的拟合能力,又能减小过拟合风险. 针对 \(ReLU/PReLU\) 的矫正非线性 ...

  8. python基础知识-04-字符串列表元组

    python其他知识目录 内存,cpu,硬盘,解释器 实时翻译 编译器 :一次性翻译python2,3 除法,2不能得小数,3能得小数 1.字符串操作 1.1字符串操作startswith start ...

  9. PHP开发中常见的漏洞及防范

    PHP开发中常见的漏洞及防范 对于PHP的漏洞,目前常见的漏洞有五种.分别是Session文件漏洞.SQL注入漏洞.脚本命令执行漏洞.全局变量漏洞和文件漏洞.这里分别对这些漏洞进行简要的介绍和防范. ...

  10. myeclipse生成类的帮助文档

    http://blog.csdn.net/tabactivity/article/details/11807233