java算法-单向队列

队列是一种:先进先出,后进后出的数据结构

单项队列: 从前面删除元素,从后面插入元素,跟现实中排队是一样的道理

这里我们用指针移动位置的方法。因为数组删除元素,如果我们要跟现实中排队效果一样,就需要移动数组,很浪费时间和空间。

所以:

>添加元素时,当尾部到达数组末尾的时候,我们就把他指向头部

>删除元素时,当头部到达数组末尾的时候,我们就把头部重置,即指向0

package com.ghostwu;

class Queue {
    
    private Object[] queueArr;
    private int maxSize; //总大小
    private int front; //
    private int rear;  //
    private int realNums; //队列真实长度
    
    public Queue( int _n ){
        maxSize = _n;
        queueArr = new Object[maxSize];
        front = 0;
        rear = -1;
        realNums = 0;
    }
    
    public void append( int value ){
        if( isFull() ){
            System.out.println( "队列满了" );
        }else {
            if( rear == maxSize - 1 ){ //尾部满了,把指针指到头部
                rear = -1;
            }
            queueArr[++rear] = value;
            realNums++;
        }
    }
    
    public Object shift(){
        Object value = null;
        if( !isEmpty() ){
            value = peekFront();
            queueArr[front] = null;
            front++;
            if( front == maxSize ){
                front = 0;
            }
            realNums--;
        }
        return value;
    }
    
    public Object peekFront(){
        return queueArr[front];
    }
    
    public boolean isFull(){
        return realNums == maxSize;
    }
    
    public boolean isEmpty(){
        return realNums == 0;
    }
    
    public int getSize(){
        return realNums;
    }
    
    public void print(){
        for( int i = 0; i < queueArr.length; i++ ){
            System.out.print( queueArr[i] + "\t" );
        }
    }
}

public class MyQueue {

    public static void main(String[] args) {
        
        Queue q = new Queue( 5 );
        q.append( 10 );
        q.append( 20 );
        q.append( 30 );
        q.append( 40 );
        q.append( 50 );
        
        System.out.println( q.peekFront() );
        System.out.println( q.getSize() );
        q.shift();
        System.out.println( q.peekFront() );
        q.print();
        q.append( 100 );
        q.append( 200 );
    }

}

 

posted @ 2018-07-09 23:32  ghostwu  阅读(979)  评论(0编辑  收藏  举报
Copyright ©2017 ghostwu