数据结构之循环队列
循环队列是首位相连的一种队列,它也是一种受限的队列,队列遵守先进先出原则
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; import MyStack.MyLinkStack; 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; } } }
测试类Test
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()); } }