1.循环队列的封装
package com.pinjia.shop.common.collection;
/**
* Created by wangwei on 2016/12/29.
* 循环队列的自我封装
*/
public class Myqueue<E> {
E[] a;//数组对象
private static final int DEFAULT_SIZE = 10;//默认队列初始化大小
int front;
int rear;
public Myqueue(){
this(DEFAULT_SIZE);
}
public Myqueue(int size){
a = (E[])new Object[size];
front = 0;
rear = 0;
}
public boolean inQueue(E obj){
if((rear+1)%a.length==front){ //队满
return false;
}else{
a[rear] = obj;
rear = (rear+1)%a.length;
return true;
}
}
public E outQueue(){
if(front == rear){
return null;
}else{
E obj = a[front];
front = (front+1)%a.length;
return obj;
}
}
public int length(){
if(rear>front)
return rear-front+1;
else
return a.length;
}
public boolean isEmpty(){
return rear == front;
}
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i=0;i<a.length;i++){
sb.append(outQueue()+""+",");
}
return sb.toString().substring(0,sb.toString().lastIndexOf(","));
}
public static void main(String[] args) {
Myqueue<Integer> myqueue = new Myqueue<Integer>(12);
System.out.println(myqueue.length());
myqueue.inQueue(1);
myqueue.inQueue(2);
myqueue.inQueue(3);
myqueue.inQueue(4);
System.out.println(myqueue.toString());
}
}
2.链式队列的封装
package com.pinjia.shop.common.collection;
import java.util.LinkedList;
/**
* Created by wangwei on 2016/12/29.
*/
public class LinkedQueue<T> {
//定义链式数据结构
private class Node{
private Node next;
private T data;
public Node(){}
public Node(T data,Node next){
this.next = next;
this.data = data;
}
}
private Node front;
private Node rear;
private int size = 0;
public LinkedQueue(){
Node s = new Node(null,null);
s.next = null;
front = rear = s;
}
//入队
public void inQueue(T data){
Node node = new Node(data,null);
rear.next = node;
rear = node;
size++;
}
//出队
public T outQueue(){
if(front == rear) //空队列
return null;
else{
Node p = front.next;
T x = p.data;
front.next = front.next.next;
if(p.next==null)rear = front;
p = null;
size--;
return x;
}
}
/**
* 队列长队
* @return
* @author WWX
*/
public int size(){
return size;
}
/**
* 判断队列是否为空
* @return
* @author WWX
*/
public boolean isEmpty(){
return size==0;
}
public String toString() {
if(isEmpty()){
return "[]";
}else{
StringBuilder sb = new StringBuilder("[");
for(Node current=front.next;current!=null;current=current.next){
sb.append(current.data.toString() + ", ");
}
int len = sb.length();
return sb.delete(len - 2, len).append("]").toString();
}
}
public static void main(String[] args) {
LinkedQueue<Integer> queue=new LinkedQueue<Integer>();
queue.inQueue(1);
queue.inQueue(2);
queue.inQueue(3);
queue.inQueue(4);
queue.inQueue(5);
queue.inQueue(6);
System.out.println(queue);
System.out.println("出队:"+queue.outQueue());
System.out.println("队列长度="+queue.size());
System.out.println(queue);
System.out.println("出队:"+queue.outQueue());
System.out.println("队列长度="+queue.size());
System.out.println(queue);
System.out.println("出队:"+queue.outQueue());
System.out.println("队列长度="+queue.size());
System.out.println(queue);
}
}