花间一壶酒

导航

循环队列-顺序存储-Java实现

package com.wrh.lab.dataStructure.stackAndQueue;

/**
* the interface of queue
*
@author wrh
*
*
@param <E>
*/
public interface Queue<E> {

/**
* enqueue the element
*
@param element
*/
public void enqueue(E element);

/**
*
*
@return the dequeue element
*/
public E dequeue();

/**
* get the first element of the queue
*
@return the first element of the queue
*/
public E getFirstVal();

/**
*
*
@return true for empty and false for not empty
*/
public boolean isEmpty();

/**
* clear the queue
*/
public void clear();
}

 

package com.wrh.lab.dataStructure.stackAndQueue;

public class QueueNode<E> {

private E element;
private QueueNode<E> next;

/**
*
*/
public QueueNode() {
element = null;
next = null;
}

public QueueNode(E element, QueueNode<E> next) {
this.element = element;
this.next = next;
}

public E getElement() {
return element;
}

/**
*
@param element
*/
public void setElement(E element) {
this.element = element;
}

public QueueNode<E> getNext() {
return next;
}

public void setNext(QueueNode<E> next) {
this.next = next;
}
}

 

package com.wrh.lab.dataStructure.stackAndQueueImpl;
/**
*
@author wrh
* the implement of the circular sequence queue
*/
import com.trs.lab.dataStructure.stackAndQueue.Queue;

public class CircularSeqQueueImpl<E> implements Queue<E> {
private static final int defaultSize = 10;
private int size;
private int front;
private int rear;
private E[] listArray;

public CircularSeqQueueImpl() {
size = defaultSize + 1;
front = rear = 0;
listArray = (E[]) new Object[size];
}

public CircularSeqQueueImpl(int size) {
this.size = size + 1;
front = rear = 0;
listArray = (E[]) new Object[size];
}

@Override
public void enqueue(E element) {
if (((rear + 1 ) % size) == front) {
System.out.println("the queue is full");
} else {
rear = (rear + 1) % size;
listArray[rear] = element;
}
}

@Override
public E dequeue() {
if (isEmpty()) {
System.out.println("the queue is empty!");
return null;
} else {
front = (front + 1) % size;
return listArray[front];
}
}

@Override
public E getFirstVal() {
if (isEmpty()) {
System.out.println("the queue is empty");
return null;
} else {
return listArray[(front + 1) % size];
}
}

@Override
public boolean isEmpty() {
return front == rear;
}

@Override
public void clear() {
front = rear = 0;
}

public static void main(String[] args) {
Queue<Integer> q = new CircularSeqQueueImpl<Integer>(8);
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(4);
q.enqueue(4);
q.enqueue(4);
System.out.println(q.dequeue());
System.out.println(q.dequeue());
System.out.println(q.dequeue());
System.out.println(q.dequeue());
}

}




posted on 2012-02-16 17:17  wrh526  阅读(472)  评论(0编辑  收藏  举报