Java數組實現堆棧和隊列__資料結構(Java版)

來源:互聯網
上載者:User
數組堆棧:public class Stack {private long[] stackArray;private int top;private int maxSize;public Stack(int maxSize){this.maxSize = maxSize;top = -1;stackArray = new long[maxSize];}public void push(long value){stackArray[++top] = value;//maxSize++;}public long pop(){return stackArray[top--];}public boolean isEmpty(){return top == -1;}public boolean isFull(){return maxSize == (top+1);}public long getTopValue(){return stackArray[top];}}測試類別:<pre name="code" class="java">class stackApp{public static void main(String args[]){Stack stack = new Stack(10);stack.push(1);stack.push(2);stack.push(3);stack.push(4);while(!stack.isEmpty()){long value = stack.pop();System.out.println(" "+value);}//while} }

數組隊列:
class queue{
    private long[] array;
    private int front;
    private int rear;
    private int nElements;
    private int maxSize;
    
    public queue(int s){
        maxSize = s;
        array = new long[maxSize];
        front = 0;
        rear = -1;
        nElements = 0;
    }
    public void insert(long value){
        if(rear == maxSize-1){
            rear = -1;
        }
        array[++rear] = value;
        nElements++;
    }
    public long remove(){
        if(front+1 == maxSize){
            front = 0;
        }
        nElements--;
        return array[front++];
    }
    public long getFrontElement(){
        return array[front];
    }
    public boolean isEmpty(){
        return (nElements == 0);
    }
    public boolean isFull(){
        return (maxSize == nElements);
    }
    public int getNElements(){
        return nElements;
    }
}
測試類別:
class queueApp{
    public static void main(String args[]){
        queue que = new queue(10);
        que.insert(10);
        que.insert(20);
        que.insert(30);
        que.insert(40);
        que.insert(50);
        
        while(!que.isEmpty()){
            long temp = que.remove();
            System.out.println(" "+temp);
        }
    }
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.