什么是队列: 先进先出
循环队列:
package com.tuln.datastract;
class QueueDemo{
private int front;
private int rear;
private int[] elem;
private int usedSize=0;
private int allSize=10;
public QueueDemo(){
this(10);
}
public QueueDemo(int val){
this.elem=new int [val];
this.front=0;
this.rear=0;
}
public void push(int val){
if(isFull()){
throw new UnsupportedOperationException("队列已满");
}
elem[this.rear]=val;
rear=++rear % allSize;
this.usedSize++;
}
public void pop(){
if(isEmpty()){
throw new UnsupportedOperationException("栈为空");
}
front = ++front%allSize;
this.usedSize--;
}
public boolean isEmpty(){
if(rear==front){
return true;
}
return false;
}
public Boolean isFull(){
if((rear+1)%allSize==this.front){
return true;
}
return false;
}
public void show(){
int i=front;
System.out.println("队列元素为: ");
while(i!=rear){
System.out.print(elem[i]+" ");
i=(i+1)%allSize;
}
}
}
public class TestQueueDemo {
}
链式队列
package com.tuln.datastract;
class LinkQueue{
class Entry{
private int data;
private Entry next;
Entry(){
this.data=0;
this.next=null;
}
Entry(int val){
this.data=val;
this.next=null;
}
private Entry front=null;
private Entry rear=null;
private int usedSize=0;
public void push(int val){
Entry cur=new Entry(val);
if(front==null&&rear==null){
front=cur;
rear=front;
}else{
rear.next=cur;
rear=rear.next;
}
this.usedSize++;
}
public void pop(){
if(Empty()){
throw new UnsupportedOperationException("链表队列为空");
}
front=front.next;
usedSize--;
}
public boolean Empty(){
if(front==rear){
return true;
}
return false;
}
public void show(){
Entry cur=front;
while(cur!=null){
System.out.println(cur.data);
cur=cur.next;
}
}
}
}
public class LinkQueueDemo {
public static void main(String[] args) {
LinkQueue lk=new LinkQueue();
}
}