- public interface MyStack<T> {
- /**
- * 判断栈是否为空
- */
- boolean isEmpty();
- /**
- * 清空栈
- */
- void clear();
- /**
- * 栈的长度
- */
- int length();
- /**
- * 数据入栈
- */
- boolean push(T data);
- /**
- * 数据出栈
- */
- T pop();
- }
栈的数组实现, 底层使用数组:
Java代码
- public class MyArrayStack<T> implements MyStack<T> {
- private Object[] objs = new Object[16];
- private int size = 0;
- @Override
- public boolean isEmpty() {
- return size == 0;
- }
- @Override
- public void clear() {
- // 将数组中的数据置为null, 方便GC进行回收
- for (int i = 0; i < size; i++) {
- objs[size] = null;
- }
- size = 0;
- }
- @Override
- public int length() {
- return size;
- }
- @Override
- public boolean push(T data) {
- // 判断是否需要进行数组扩容
- if (size >= objs.length) {
- resize();
- }
- objs[size++] = data;
- return true;
- }
- /**
- * 数组扩容
- */
- private void resize() {
- Object[] temp = new Object[objs.length * 3 / 2 + 1];
- for (int i = 0; i < size; i++) {
- temp[i] = objs[i];
- objs[i] = null;
- }
- objs = temp;
- }
- @SuppressWarnings("unchecked")
- @Override
- public T pop() {
- if (size == 0) {
- return null;
- }
- return (T) objs[--size];
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("MyArrayStack: [");
- for (int i = 0; i < size; i++) {
- sb.append(objs[i].toString());
- if (i != size - 1) {
- sb.append(", ");
- }
- }
- sb.append("]");
- return sb.toString();
- }
- }
栈的链表实现, 底层使用链表:
Java代码
- public class MyLinkedStack<T> implements MyStack<T> {
- /**
- * 栈顶指针
- */
- private Node top;
- /**
- * 栈的长度
- */
- private int size;
- public MyLinkedStack() {
- top = null;
- size = 0;
- }
- @Override
- public boolean isEmpty() {
- return size == 0;
- }
- @Override
- public void clear() {
- top = null;
- size = 0;
- }
- @Override
- public int length() {
- return size;
- }
- @Override
- public boolean push(T data) {
- Node node = new Node();
- node.data = data;
- node.pre = top;
- // 改变栈顶指针
- top = node;
- size++;
- return true;
- }
- @Override
- public T pop() {
- if (top != null) {
- Node node = top;
- // 改变栈顶指针
- top = top.pre;
- size--;
- return node.data;
- }
- return null;
- }
- /**
- * 将数据封装成结点
- */
- private final class Node {
- private Node pre;
- private T data;
- }
- }
两种实现的比较, 主要比较数据入栈和出栈的速度:
Java代码
- @Test
- public void testSpeed() {
- MyStack<Person> stack = new MyArrayStack<Person>();
- int num = 10000000;
- long start = System.currentTimeMillis();
- for (int i = 0; i < num; i++) {
- stack.push(new Person("xing", 25));
- }
- long temp = System.currentTimeMillis();
- System.out.println("push time: " + (temp - start));
- while (stack.pop() != null)
- ;
- System.out.println("pop time: " + (System.currentTimeMillis() - temp));
- }
MyArrayStack中入栈和出栈10,000,000条数据的时间:
push time: 936
pop time: 47
将MyArrayStack改为MyLinkedStack后入栈和出栈的时间:
push time: 936
pop time: 126
可见两者的入栈速度差不多, 出栈速度MyArrayStack则有明显的优势.
为什么测试结果是这样的? 可能有些朋友的想法是数组实现的栈应该具有更快的遍历速度, 但增删速度应该比不上链表实现的栈才对. 但是栈中数据的增删具有特殊性: 只在栈顶入栈和出栈. 也就是说数组实现的栈在增加和删除元素时并不需要移动大量的元素, 只是在数组扩容时需要进行复制. 而链表实现的栈入栈和出栈时都需要将数据包装成Node或者从Node中取出数据, 还需要维护栈顶指针和前驱指针.
栈的应用举例
1. 将10进制正整数num转换为n进制
Java代码
- private String conversion(int num, int n) {
- MyStack<Integer> myStack = new MyArrayStack<Integer>();
- Integer result = num;
- while (true) {
- // 将余数入栈
- myStack.push(result % n);
- result = result / n;
- if (result == 0) {
- break;
- }
- }
- StringBuilder sb = new StringBuilder();
- // 按出栈的顺序倒序排列即可
- while ((result = myStack.pop()) != null) {
- sb.append(result);
- }
- return sb.toString();
- }
2. 检验符号是否匹配. '['和']', '('和')'成对出现时字符串合法. 例如"[][]()", "[[([]([])()[])]]"是合法的; "([(])", "[())"是不合法的.
遍历字符串的每一个char, 将char与栈顶元素比较. 如果char和栈顶元素配对, 则char不入栈, 否则将char入栈. 当遍历完成时栈为空说明字符串是合法的.
Java代码
- public boolean isMatch(String str) {
- MyStack<Character> myStack = new MyArrayStack<Character>();
- char[] arr = str.toCharArray();
- for (char c : arr) {
- Character temp = myStack.pop();
- // 栈为空时只将c入栈
- if (temp == null) {
- myStack.push(c);
- }
- // 配对时c不入栈
- else if (temp == '[' && c == ']') {
- }
- // 配对时c不入栈
- else if (temp == '(' && c == ')') {
- }
- // 不配对时c入栈
- else {
- myStack.push(temp);
- myStack.push(c);
- }
- }
- return myStack.isEmpty();
- }
3. 行编辑: 输入行中字符'#'表示退格, '@'表示之前的输入全都无效.
使用栈保存输入的字符, 如果遇到'#'就将栈顶出栈, 如果遇到@就清空栈. 输入完成时将栈中所有字符出栈后反转就是输入的结果:
Java代码
- private String lineEdit(String input) {
- MyStack<Character> myStack = new MyArrayStack<Character>();
- char[] arr = input.toCharArray();
- for (char c : arr) {
- if (c == '#') {
- myStack.pop();
- } else if (c == '@') {
- myStack.clear();
- } else {
- myStack.push(c);
- }
- }
- StringBuilder sb = new StringBuilder();
- Character temp = null;
- while ((temp = myStack.pop()) != null) {
- sb.append(temp);
- }
- // 反转字符串
- sb.reverse();
- return sb.toString();
- }
或者
栈数组实现一:优点:入栈和出栈速度快,缺点:长度有限(有时候这也不能算是个缺点)
[java]
- public class Stack {
- private int top = -1;
- private Object[] objs;
- public Stack(int capacity) throws Exception{
- if(capacity < 0)
- throw new Exception("Illegal capacity:"+capacity);
- objs = new Object[capacity];
- }
- public void push(Object obj) throws Exception{
- if(top == objs.length - 1)
- throw new Exception("Stack is full!");
- objs[++top] = obj;
- }
- public Object pop() throws Exception{
- if(top == -1)
- throw new Exception("Stack is empty!");
- return objs[top--];
- }
- public void dispaly(){
- System.out.print("bottom -> top: | ");
- for(int i = 0 ; i <= top ; i++){
- System.out.print(objs[i]+" | ");
- }
- System.out.print("\n");
- }
- public static void main(String[] args) throws Exception{
- Stack s = new Stack(2);
- s.push(1);
- s.push(2);
- s.dispaly();
- System.out.println(s.pop());
- s.dispaly();
- s.push(99);
- s.dispaly();
- s.push(99);
- }
- }
[plain]
- bottom -> top: | 1 | 2 |
- 2
- bottom -> top: | 1 |
- bottom -> top: | 1 | 99 |
- Exception in thread "main" java.lang.Exception: Stack is full!
- at Stack.push(Stack.java:17)
- at Stack.main(Stack.java:44)
数据项入栈和出栈的时间复杂度都为常数O(1)
栈数组实现二:优点:无长度限制,缺点:入栈慢
[java]
- import java.util.Arrays;
- public class UnboundedStack {
- private int top = -1;
- private Object[] objs;
- public UnboundedStack() throws Exception{
- this(10);
- }
- public UnboundedStack(int capacity) throws Exception{
- if(capacity < 0)
- throw new Exception("Illegal capacity:"+capacity);
- objs = new Object[capacity];
- }
- public void push(Object obj){
- if(top == objs.length - 1){
- this.enlarge();
- }
- objs[++top] = obj;
- }
- public Object pop() throws Exception{
- if(top == -1)
- throw new Exception("Stack is empty!");
- return objs[top--];
- }
- private void enlarge(){
- int num = objs.length/3;
- if(num == 0)
- num = 1;
- objs = Arrays.copyOf(objs, objs.length + num);
- }
- public void dispaly(){
- System.out.print("bottom -> top: | ");
- for(int i = 0 ; i <= top ; i++){
- System.out.print(objs[i]+" | ");
- }
- System.out.print("\n");
- }
- public static void main(String[] args) throws Exception{
- UnboundedStack us = new UnboundedStack(2);
- us.push(1);
- us.push(2);
- us.dispaly();
- System.out.println(us.pop());
- us.dispaly();
- us.push(99);
- us.dispaly();
- us.push(99);
- us.dispaly();
- }
- }
[plain]
- bottom -> top: | 1 | 2 |
- 2
- bottom -> top: | 1 |
- bottom -> top: | 1 | 99 |
- bottom -> top: | 1 | 99 | 99 |
由于该栈是由数组实现的,数组的长度是固定的,当栈空间不足时,必须将原数组数据复制到一个更长的数组中,考虑到入栈时或许需要进行数组复制,平均需要复制N/2个数据项,故入栈的时间复杂度为O(N),出栈的时间复杂度依然为O(1)
栈单链表实现:没有长度限制,并且出栈和入栈速度都很快
[java]
- public class LinkedList {
- private class Data{
- private Object obj;
- private Data next = null;
- Data(Object obj){
- this.obj = obj;
- }
- }
- private Data first = null;
- public void insertFirst(Object obj){
- Data data = new Data(obj);
- data.next = first;
- first = data;
- }
- public Object deleteFirst() throws Exception{
- if(first == null)
- throw new Exception("empty!");
- Data temp = first;
- first = first.next;
- return temp.obj;
- }
- public void display(){
- if(first == null)
- System.out.println("empty");
- System.out.print("top -> bottom : | ");
- Data cur = first;
- while(cur != null){
- System.out.print(cur.obj.toString() + " | ");
- cur = cur.next;
- }
- System.out.print("\n");
- }
- }
[java]
- public class LinkedListStack {
- private LinkedList ll = new LinkedList();
- public void push(Object obj){
- ll.insertFirst(obj);
- }
- public Object pop() throws Exception{
- return ll.deleteFirst();
- }
- public void display(){
- ll.display();
- }
- public static void main(String[] args) throws Exception{
- LinkedListStack lls = new LinkedListStack();
- lls.push(1);
- lls.push(2);
- lls.push(3);
- lls.display();
- System.out.println(lls.pop());
- lls.display();
- }
- }
[plain]
- top -> bottom : | 3 | 2 | 1 |
- 3
- top -> bottom : | 2 | 1 |
数据项入栈和出栈的时间复杂度都为常数O(1)
/** * 基于数组实现的顺序栈 * @param*/public class Stack { private Object[] data = null; private int maxSize=0; //栈容量 private int top =-1; //栈顶指针 /** * 构造函数:根据给定的size初始化栈 */ Stack(){ this(10); //默认栈大小为10 } Stack(int initialSize){ if(initialSize >=0){ this.maxSize = initialSize; data = new Object[initialSize]; top = -1; }else{ throw new RuntimeException("初始化大小不能小于0:" + initialSize); } } //判空 public boolean empty(){ return top==-1 ? true : false; } //进栈,第一个元素top=0; public boolean push(E e){ if(top == maxSize -1){ throw new RuntimeException("栈已满,无法将元素入栈!"); }else{ data[++top]=e; return true; } } //查看栈顶元素但不移除 public E peek(){ if(top == -1){ throw new RuntimeException("栈为空!"); }else{ return (E)data[top]; } } //弹出栈顶元素 public E pop(){ if(top == -1){ throw new RuntimeException("栈为空!"); }else{ return (E)data[top--]; } } //返回对象在堆栈中的位置,以 1 为基数 public int search(E e){ int i=top; while(top != -1){ if(peek() != e){ top --; }else{ break; } } int result = top+1; top = i; return result; }}
栈的链式存储结构实现:
public class LinkStack{ //链栈的节点 private class Node { E e; Node next; public Node(){} public Node(E e, Node next){ this.e = e; this.next = next; } } private Node top; //栈顶元素 private int size; //当前栈大小 public LinkStack(){ top = null; } //当前栈大小 public int length(){ return size; } //判空 public boolean empty(){ return size==0; } //入栈:让top指向新创建的元素,新元素的next引用指向原来的栈顶元素 public boolean push(E e){ top = new Node(e,top); size ++; return true; } //查看栈顶元素但不删除 public Node peek(){ if(empty()){ throw new RuntimeException("空栈异常!"); }else{ return top; } } //出栈 public Node pop(){ if(empty()){ throw new RuntimeException("空栈异常!"); }else{ Node value = top; //得到栈顶元素 top = top.next; //让top引用指向原栈顶元素的下一个元素 value.next = null; //释放原栈顶元素的next引用 size --; return value; } }}
基于LinkedList实现的栈结构:
import java.util.LinkedList;/** * 基于LinkedList实现栈 * 在LinkedList实力中只选择部分基于栈实现的接口 */public class StackList{ private LinkedList ll = new LinkedList (); //入栈 public void push(E e){ ll.addFirst(e); } //查看栈顶元素但不移除 public E peek(){ return ll.getFirst(); } //出栈 public E pop(){ return ll.removeFirst(); } //判空 public boolean empty(){ return ll.isEmpty(); } //打印栈元素 public String toString(){ return ll.toString(); }}