堆棧

 順序棧:函數

定義一個接口:IStack<E>spa

public interface IStack<E> {
    E push(E item);
    E pop();
    E peek();
    int size();
    boolean empty();
     
}

定義一個SeqStack<E>類實現棧的抽象數據類型類code

public class SeqStack<E> implements IStack<E> {
    
    private int maxsize;
    private E[] data;
    private int top;
    
    //初始化棧
    
    public SeqStack(Class<E> type,int size){
        data=(E[]) Array.newInstance(type, size);
        maxsize=size;
        top=-1;
    }
    
    //入棧
    public E push(E item) {
        // TODO Auto-generated method stub
        if(!isFull()){
            data[++top]=item;
            return item;
        }else
        return null;
    }
    
    //棧是否爲滿
    public boolean isFull() {
        // TODO Auto-generated method stub
        if(top==maxsize-1){
            return true;
        }else{
            return false;
        }
        
    }

    //出棧操做
    public E pop() {
        E item=null;
        if(!empty()){
            item=data[top--];
        }
        
        return item;
    }

    //獲取棧頂元素
    public E peek() {
        // TODO Auto-generated method stub
        E item=null;
        if(!empty()){
            item=data[top];
        }
        return item;
    }

    public int size() {
        // TODO Auto-generated method stub
        return top+1;
    }

    public boolean empty() {
        // TODO Auto-generated method stub
        if(top==-1){
            return true;
        }else
        return false;
    }

}

主函數實現blog

public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] data={33,45,3,7,5};
        SeqStack<Integer> stack=new SeqStack<Integer>(Integer.class,data.length);
        //入棧
        System.out.println("******入棧*******");
        for(int i=0;i<data.length;i++){
            stack.push(data[i]);
            System.out.println(data[i]+"入棧");
        }
        
        int size=stack.size();
        System.out.println(size+"*******");
        //出棧
        System.out.println("***出棧****");
        for(int i=0;i<data.length;i++){
            stack.pop();
            System.out.println(stack.pop()+"出棧");
        }
        
    }
相關文章
相關標籤/搜索