A little bit of progress every day, insisted that success.
1, queue
/ ** * No one is perfect, if any bug, also please correct me * continue to learn Java data structures ---- queue (queue) * queue and stack, are using an array, but more of a head-of-queue, team data access head, the tail is inserted into the data * important characteristic data FIFO queue ---- * enqueue, dequeue, the full team, the team space, see * / public class queue { Private Long ARR []; Private int Maxsize ; // maximum capacity private int front; // HOL, data access private int rear; // the tail, inserting the data private int elements; // valid data public Queue (int size) { this.Maxsize = size; ARR = Long new new [Maxsize]; Front = 0; // start at index 0 accessed rear = -1; // stack pointers corresponds Elements = 0; } // valid data public void Show () { System.out.println (Elements); } // Check the current data point public Long PEEK () { return arr[front]; } // 入队 public void add(int value) { arr[++rear] = value; elements++; } // 出队 public long remove() { long value = arr[front++];// 队头从0开始 elements--; return value; } // 队满 public boolean isEmpty() { return elements == 0; } // 队空 public boolean isFull() { return elements == Maxsize; } public static void main(String[] args) { Queue q = new Queue(3); q.add(52); q.add(2); q.add(6); while(!q.isEmpty()){ System.out.print (q.remove () + "" ); // FIFO } } }
2, a circular queue
Queue plagued by problems, exceed the maximum length will throw an exception, this is not good, so we must understand the circular queue, adding even more than is feasible in length.
// circular queue public class Queue { Private Long ARR []; Private int Maxsize; // maximum capacity private int front; // HOL, data access private int rear; // the tail, inserting the data private int elements; // data valid public Queue (int size) { this.Maxsize = size; ARR = new new Long [Maxsize]; Front = 0; // start at index 0 accessed rear = -1; // stack pointers corresponding to elements = 0 ; } // valid data public void Show () { System.out.println (Elements); } // check the current point data public Long PEEK () { return ARR [Front]; } // enqueue public void add (int value) { IF (REAR arr.length == -. 1) {// REAR initial value of -1, the subscript 0-99 rear = -1; // reset the tail } arr [++ rear] = value; // this time point to a first position Elements ++; } // dequeue public Long Remove () { Long ARR value = [Front ++]; // implementation of the first sentence, front is equal arr.length iF (== Front arr.length) {//. 1 + 2. 3 = Front = 0; // reset HOL } elements--; return value; } / / team full public Boolean isEmpty () { return Elements == 0; } // null force public Boolean isFull () { return Elements == Maxsize; } public static void main (String [] args) { Queue Queue new new Q = ( . 3); q.add (52 is); q.add (2); q.add (. 6); q.add (. 6); q.add (. 6); {the while (q.isEmpty ()!) of System.out.print (q.remove () + ""); // FIFO } } }