# 数据结构之循环队列

java实现循环队列

Node实现类

package MyCycleQueue;

public class Node {
private Object data;
private Node next;
private Node before;

public Node(){}
public Node(Object data){
super();
this.data = data;

}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

public Node getBefore() {
return before;
}

public void setBefore(Node before) {
this.before = before;
}
}

MyCycleQueue实现类

package MyCycleQueue;

public class MyCycleQueue {
private Node root;
private Node rear;
private Node front;
private int maxsize;
private int size;

// push
public void push(Object data){
Node node = new Node();
if (front ==rear && size==0){
root = new Node(data);
front = root;
rear = node;
root.setNext(rear);
rear.setNext(front);
next = node;
size ++;
}else {
rear.setData(data);
rear.setNext(node);
rear = node;
rear.setNext(root);
next =node;
size ++;

}
}

// pop
public Object pop() throws Exception {
if (root == front && size !=0){
Object data = front.getData();
front = root.getNext();
size--;
return data;
}else if (size ==0){
throw new Exception("队列为空");
}else {
Object data = front.getData();
front = front.getNext();
size--;
return data;
}
}

}

package MyCycleQueue;

public class test {
public static void main(String[] args) throws Exception {
MyCycleQueue myCycleQueue = new MyCycleQueue();
myCycleQueue.push(1);
myCycleQueue.push(2);
myCycleQueue.push(3);
myCycleQueue.push(4);
myCycleQueue.push(5);
//        myCycleQueue.pop();
//        myCycleQueue.pop();
//        myCycleQueue.pop();
//        myCycleQueue.pop();
//        myCycleQueue.pop();
System.out.println(myCycleQueue.pop());
System.out.println(myCycleQueue.pop());
System.out.println(myCycleQueue.pop());
System.out.println(myCycleQueue.pop());
System.out.println(myCycleQueue.pop());
System.out.println(myCycleQueue.pop());

}
}

posted @ 2020-09-06 22:16  wigginess  阅读(191)  评论(0编辑  收藏  举报