数据结构与算法(3)—— 队列(java)

xiaoxiao2022-06-11  26

1 数组实现的队列

public class ArrayQueue { private String[] items; private int n=0; //数组的大小 private int head=0; private int tail = 0; public ArrayQueue(int capacity){ items = new String[capacity]; n = capacity; } //入队列 public boolean enQueue(String item){ // tail == n,表示队列已满 if(tail == n) return fasle; else{ items[tail++] = item; return true; } } //出队列 public String deQueue(){ // head==tail,表示队列空 if(head == tail) return null; else{ String s = items[head]; ++head; return s; } } }

2 简单循环数组实现队列

public class ArrayQueue { private int front; private int rear; private int capacity; private int[] array; private ArrayQueue(int size){ capacity = size; front = -1; rear = -1; array = new int[size]; } public static ArrayQueue createQueue(int size){ return new ArrayQueue(szie); } public boolean isEmpty(){ return front == -1; } public boolean isFull(){ retrun (rear+1) % capacity == front; } public int getQueueSize(){ return (capacity - front + rear+1) % capacity; } public void enQueue(int data){ if(isFull()) { throw new QueueOverFlowException("OverFlow"); }else{ rear = (rear + 1) % capacity; array[rear] = data; if(front == -1) { front = rear; } } } public void deQueue(){ int data = null; if(isEmpty()) { throw new EmptyQueueException("Empty"); }else{ data = array[front]; if(front == rear) { front = rear -1; }else{ front = (front + 1) % capacity; } return data; } } }

3 基于链表实现队列

public class LLQueue { private LLNode frontNode; private LLNode rearNode; private LLQueue(){ this.frontNode = null; this.rearNode = null; } public static LLQueue createQueue { return new LLQueue(); } public boolean isEmpty(){ return frontNode == null; } public void enQueue(int data){ LLNode newNode = new LLNode(data); if(rearNode != null) { rearNode.setNext(newNode); } rearNode = newNode; if(frontNode == null) { frontNode = rearNode; } } public int deQueue(){ int data = null; if(isEmpty()) { throw new EmptyQueueException("Empty"); }else{ data = frontNode.getData(); frontNode = frontNode.getNext(); } return data; } }
转载请注明原文地址: https://www.6miu.com/read-4931919.html

最新回复(0)