顺序存储
package linearlist;
/**
* 栈的顺序存储结构
* @author mac
* */
public class ArrayStack {
private static final int DEFAULT_CAPACITY = 10;
private Object[] items;
private int size;
private int capacity;
public ArrayStack(){
this.capacity = DEFAULT_CAPACITY;
items = new Object[capacity];
size = 0;
}
public ArrayStack(int capacity) {
this.capacity = capacity;
items = new Object[capacity];
size = 0;
}
public int size(){
return size;
}
public boolean isEmpty(){
return this.size == 0;
}
/**
* 入栈
* */
public void push(Object element) {
ensureCapacity(size() + 1);
items[size ++] = element;
}
/**
* 出栈
* */
public Object pop(){
if(!isEmpty()){
Object elem = items[size - 1];
items[--size] = null;
return elem;
}
return null;
}
public Object peek(){
if(!isEmpty()) {
return items[size - 1];
}
return null;
}
/**
* 扩容,类似于ArrayList
* */
private void ensureCapacity(int newCapacity) {
int oldCapacity = items.length;
if(newCapacity <= oldCapacity) {
return;
}
newCapacity = oldCapacity * 2 + 1;
Object[] oldData = items;
items = new Object[newCapacity];
for(int i = 0;i < oldData.length;i ++) {
items[i] = oldData[i];
}
}
}
链式存储
package linearlist;
/**
* 栈的链式存储结构.
* @author mac
* */
public class LinkedStack<T> {
private Node<T> top;
private int size;
/**
* 初始化
* */
public LinkedStack(){
this.top = null;
this.size = 0;
}
public LinkedStack(T element) {
top = new Node<T>(element, null);
this.size = 1;
}
/**
* 入栈
* */
public void push(T element) {
Node<T> node = new Node<T> (element, top);
top = node;
this.size ++;
}
/**
* 出栈
* */
public T pop(){
if(!isEmpty()) {
Node<T> oldTop = top;
top = top.next;
oldTop.next = null;
this.size--;
return oldTop.data;
}
return null;
}
public T peek(){
if(!isEmpty()) {
return top.data;
}
return null;
}
/**
* 清空
* */
public void clear(){
top = null;
this.size = 0;
}
public boolean isEmpty(){
return this.size == 0;
}
/**
* 定义节点
* */
private static class Node<T> {
T data;
Node<T> next;
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
}
栈的应用
匹配字符
package linearlist;
import java.util.LinkedList;
/**
* 匹配字符是否成对
*
* [[([{}]([])()[])]] true
* ([(}]) false
* */
public class StackUsageMatch {
public static boolean isMatch(String str) {
LinkedList<Character> stack = new LinkedList<Character>();
char[] chars = str.toCharArray();
for(Character c : chars) {
Character temp = stack.poll();
if(temp == null){
stack.push(c);
}else if(temp == '[' && c == ']'){
}else if(temp == '(' && c == ')'){
}else if(temp == '{' && c == '}'){
}else if(temp == '<' && c == '>'){
}
else{
stack.push(temp);
stack.push(c);
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(isMatch("{<[()]>}"));
System.out.println(isMatch("{<(]>"));
}
}