數(shù)據(jù)結(jié)構(gòu)實(shí)例:數(shù)組實(shí)現(xiàn)一個(gè)簡(jiǎn)單的堆棧

字號(hào):

堆棧(Stack)是一個(gè)比較普通,而又特別的數(shù)據(jù)結(jié)構(gòu)。合理利用它的先進(jìn)后出(FILO),有時(shí)候會(huì)有一些比較好的作用。這里面不多講的它的應(yīng)用,而是舉一個(gè)很簡(jiǎn)單的例子來表明它的FILO特性,并用數(shù)組來實(shí)現(xiàn)一個(gè)堆棧算法。
    請(qǐng)看代碼:
    import java.util.*;
    public class TestStack{
    public static void main(String args[]){
    Stack stack = new Stack();
    for(int i=0; i<10; i++)
    stack.push("Stack"+ i);
    while(!stack.isEmpty())
    System.out.println(stack.pop());
    }
    }
    結(jié)果我就不打印了,從上面的例子中,我們可以看出Stack類的一些典型方法,比如push,pop和isEmpty方法。下面就利用數(shù)組來實(shí)現(xiàn)一個(gè)Stack算法:
    class StackOverflowException extends Exception{
    public StackOverflowException(){
    }
    }
    class StackEmptyException extends Exception{
    public StackEmptyException(){
    }
    }
    public class StackClass {
    private int stackSize;
    private int stackTop;
    private String[] array;
    public StackClass(){
    System.out.println("The current Stack capacity is 100.");
    stackSize = 100;
    stackTop = 0;
    array = new String[stackSize];
    }
    public StackClass(int size){
    if (size <= 0){
    System.out.println("The current Stack capacity is 100.");
    stackSize = 100;
    }
    stackSize = size;
    stackTop = 0;
    array = new String[stackSize];
    }
    public boolean isFullStack(){
    return stackSize == stackTop;
    }
    public boolean isEmptyStack(){
    return stackTop == 0;
    }
    public void push(String str) throws StackOverflowException{
    if (isFullStack())
    throw new StackOverflowException();
    array[stackTop] = str;
    stackTop ++;
    }
    public String pop() throws StackEmptyException{
    if (isEmptyStack())
    throw new StackEmptyException();
    stackTop --;
    return array[stackTop];
    }
    public static void main(String args[]){
    StackClass stack = new StackClass();
    try{
    stack.push("a");
    stack.push("aa");
    stack.push("aaa");
    }
    catch(StackOverflowException e){
    e.printStackTrace();
    }
    try{
    while (!stack.isEmptyStack())
    System.out.println(stack.pop());
    }
    catch(StackEmptyException e){
    e.printStackTrace();
    }
    }
    }
    輸出結(jié)果是:
    The current Stack capacity is 100.
    aaa
    aa
    a
    當(dāng)然這個(gè)堆棧的實(shí)現(xiàn)還是有許多不足的地方,比如只能存儲(chǔ)字符串型的元素,關(guān)于它的完善將在以后進(jìn)行。大家先只是看看想想吧...^_^...