STACK: a linear table that comes out first;
Stack can also be implemented through sequential storage and chain storage;
I. Sequential storage implementation
The end of the array is used as the top of the stack;
Code implementation:
package org.xiazdong.list;public class MyArrayStack<T> {private static final int DEFAULT_LENGTH = 10;private T[]t;private int length;private int top;public MyArrayStack(){t = (T[])new Object[DEFAULT_LENGTH];length = 0;top = -1;}public void push(T e){if((top+1)>=t.length){larger(t.length*2);}top++;if(top>=t.length){}t[top]=e;}public T top(){return t[top];}public T pop(){if(top<0){throw new ArrayIndexOutOfBoundsException();}T tmp = t[top];top--;return tmp;}public int getSize(){return top+1;}private void larger(int len){T[]tmp = (T[])new Object[len];for(int i=0;i<t.length;i++){tmp[i] = t[i];}t = tmp;}}II. Implementation of chain Storage
The head of the linked list acts as the top of the stack;
The code is implemented as follows:
package org.xiazdong.list;import org.xiazdong.list.MyLinkedList.Node;public class MyLinkedStack <T>{private Node top;private int count;public MyLinkedStack(){count = 0;top = null;}public T pop(){if(top==null){throw new ArrayIndexOutOfBoundsException();}T elem = top.elem;top = top.next;return elem;}public T top(){return top.elem;}public void push(T e){Node n = new Node();n.elem = e;n.next = top;top = n;}class Node{private T elem;Node next;public Node(){elem = null;next = null;}public Node(T elem,Node next){this.elem = elem;this.next = next;}}}Iii. Comparison
| |
Sequential Storage |
Chain Storage |
| Advantages |
O (1) |
The added and Deleted Values are O (1) and there is no limit on space. |
| Disadvantages |
Waste of space and Overflow |
Pointer requires space |
Iv. Stack applications
1. Recursion
Here we take the Fibonacci number as an example; FIB (n) = fib (n-1) + fib (n-2), FIB (2) = fib (1) = 1;
Recursion is inseparable from stack, and its implementation is done through stack;
2. suffix expression
We will certainly use a suffix expression when doing a calculator application. The infix expression is converted to a suffix expression, and the value obtained by the suffix expression is implemented through the stack;
Suffix expression in: http://blog.csdn.net/xiazdong/article/details/7272693