Java custom Queue and Application Based on Arrays

Source: Internet
Author: User

Java custom Queue and Application Based on Arrays

 

Java custom Queue:

 

The abstract data type of the queue is a container. The objects in the queue are arranged in a sequence. We can only access and retrieve the objects at the frontend (Front), but only at the end of the queue (Rear) insert a new object. Only by following this rule can we ensure that the first inserted object is deleted first (FIFO ). Java itself has its own Queue class package. For the purpose of learning, you have a better understanding of the Queue. self-built java Queue class is a good learning start:

Array-based implementation

 

? Sequential Array
With a fixed-length array Q to store objects, you can simply implement queues. In order to comply with the FIFO rules, how should we express and record the order of objects in the queue?
One natural way is to follow the stack implementation, and use Q [0] as the first team, and store other objects in sequence. However, each time the first element leaves the team, it is necessary to move all the subsequent elements forward to a unit. If the team leader is n, this work requires O (n) time, so the efficiency is very low.
? Loop Array
To avoid the overall movement of arrays, we can introduce the following two variables f and r:
F: always equal to the subscript of the first element of Q in the array, that is, the position of the next element
R: always equal to the subscript of the last element of Q plus one, that is, pointing to the position of the next element
At the beginning, f = r = 0, and the team is empty. Each time an object enters the queue, it is stored in Q [r], and then r is added to point to the next unit. Symmetric, each time an object leaves the queue, it will also add f to point to the new first element. In this way, each call to the front (), enqueue (), and dequeue () Methods takes a constant time.
However, this is not enough. Careful readers may have noticed that, according to the above conventions, f and r are always increasing monotonically during the life cycle of the queue. Therefore, if the capacity of the queue array is N, after N Queuing operations, the Unit pointed to by r will inevitably be out of the range of the array; after N Queuing operations, f points to a similar unit.
A simple method to solve the above problem is to perform a modulo operation with the length of the array after f or r plus each time, to ensure the legitimacy of the units referred to by it. In terms of its effect, this is equivalent to associating the header and tail of the array to form a ring structure.
Based on the above ideas, we can get the java code as shown below:

Queue class:

package com.queue;import java.util.Arrays;/** *  * @author gannyee * */public class Queue {    // Define capacity constant: CAPACITY    private static final int CAPACITY = 1024;    // Define capacity of queue    private static int capacity;    // Front of queue    private static int front;    // Tail of queue    private static int tail;    // Array for queue    private static Object[] array;    // Constructor of Queue class    public Queue() {        this.capacity = CAPACITY;        array = new Object[capacity];        front = tail = 0;    }    // Get size of queue    public static int getSize() {        if (isEmpty())            return 0;        else            return (capacity + tail - front) % capacity;    }    // Whether is empty    public static boolean isEmpty() {        return (front == tail);    }    // put element into the end of queue    public static void enqueue(Object element) throws ExceptionQueueFull {        if (getSize() == capacity - 1)            throw new ExceptionQueueFull("Queue is full");        array[tail] = element;        tail = (tail + 1) % capacity;    }    // get element from queue    public static Object dequeue() throws ExceptionQueueEmpty {        Object element;        if (isEmpty())            throw new ExceptionQueueEmpty("Queue is empty");        element = array[front];        front = (front + 1) % capacity;        return element;    }    // Get the first element for queue    public static Object frontElement() throws ExceptionQueueEmpty {        if (isEmpty())            throw new ExceptionQueueEmpty("Queue is empty");        return array[front];    }    // Travel all elements of queue    public static void getAllElements() {        Object[] arrayList = new Object[getSize()];        for (int i = front,j = 0; j < getSize(); i ++,j ++) {                arrayList[j] = array[i];        }        System.out.println("All elements of queue: "                + Arrays.toString(arrayList));    }}

Custom ExceptionStackEmpty exception class:

package com.queue;public class ExceptionQueueEmpty extends Exception {    // Constructor    public ExceptionQueueEmpty() {    }    // Constructor with parameters    public ExceptionQueueEmpty(String mag) {        System.out.println(mag);    }}

Custom ExceptionStackFull exception class

package com.queue;public class ExceptionQueueFull extends Exception {    // Constructor    public ExceptionQueueFull() {    }    // Constructor with parameters    public ExceptionQueueFull(String mag) {        System.out.println(mag);    }}

Test class:

package com.queue;/** * QueueTest * @author gannyee * */public class QueueTest {    public static void main(String[] args) {        // TODO Auto-generated method stub        Queue queue = new Queue();        System.out.println("The size of queue is: " + queue.getSize());        System.out.println("Is empty: " + queue.isEmpty());        try {            queue.enqueue(8);            queue.enqueue(3);            queue.enqueue(5);            queue.enqueue(7);            queue.enqueue(9);            queue.getAllElements();            System.out.println("The size of queue is: " + queue.getSize());            System.out.println("Is empty: " + queue.isEmpty());            System.out.println("The front element of queue: "                    + queue.frontElement());            System.out.println(queue.dequeue());            System.out.println(queue.dequeue());            System.out.println(queue.dequeue());            System.out.println(queue.dequeue());            System.out.println(queue.dequeue());            System.out.println("The size of queue is: " + queue.getSize());            System.out.println("Is empty: " + queue.isEmpty());        } catch (ExceptionQueueFull e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (ExceptionQueueEmpty e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

Test results:

The size of queue is: 0Is empty: trueAll elements of queue: [8, 3, 5, 7, 9]The size of queue is: 5Is empty: falseThe front element of queue: 883579The size of queue is: 0Is empty: true

 

Queue applications:

 

When you were a child, have you ever played the "hot potato" game: a group of children are in a circle, and a new potato is passed between them. One of the children is responsible for counting the data. Each time, the child holding the taro hand over the Taro to the neighbor on the right. Once you count to a specific number, the child holding the taro must exit and count again. The last child is the lucky one. Generally, the number rule always starts from 1. When the number is k, the child with the yam is listed, and then starts from 1 again. The question of Joseph PHUs can be expressed as: Who are the lucky winners of n children playing this game?
To answer this question, we can use the queue structure to represent n Children in a circle. At the beginning, it is assumed that the child corresponding to the first node of the queue has a yam. Then, according to the rules of the game, the "potato" is passed back to the k children (alternating k dequeue () and k enqueue () Operations ), and let her out (dequeue ()). This iteration continues until the leader (getSize () is 1.

The Java code is as follows:

package com.queue;public class QueueBuilder {    // Building string type array for queue    public static Queue queueBuild(String[] str) {        Queue queue = new Queue();        for (int i = 0; i < str.length; i++) {            try {                queue.enqueue(str[i]);            } catch (ExceptionQueueFull e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return queue;    }    // Weed out the kth kid who get the sweet potato    public static String gameWiner(Queue queue, int k)            throws ExceptionQueueFull, ExceptionQueueEmpty {        if (queue.isEmpty())            return null;        while (queue.getSize() > 1) {            queue.getAllElements();// Output recently queue            for (int i = 0; i < k - 1; i++)                queue.enqueue(queue.dequeue());            System.out.println("\n\t" + queue.dequeue() + ": Weep out");        }        return (String) queue.dequeue();    }}
package com.queue;public class QueueGame {    public static void main(String[] args) throws ExceptionQueueFull, ExceptionQueueEmpty {        // TODO Auto-generated method stub        String[] kid = {"Alice", "Bob", "Cindy", "Doug", "Ed",                        "Fred", "Gene", "Hope", "Irene", "Jack",                        "Kim", "Lance", "Mike", "Nancy", "Ollie"};        QueueBuilder qb = new QueueBuilder();        System.out.println("The luck dog is: " + qb.gameWiner(qb.queueBuild(kid), 5));    }}

Test results:

All elements of queue: [Alice, Bob, Cindy, Doug, Ed, Fred, Gene, Hope, Irene, Jack, Kim, Lance, Mike, Nancy, Ollie]    Ed: weep outAll elements of queue: [Fred, Gene, Hope, Irene, Jack, Kim, Lance, Mike, Nancy, Ollie, Alice, Bob, Cindy, Doug]    Jack: weep outAll elements of queue: [Kim, Lance, Mike, Nancy, Ollie, Alice, Bob, Cindy, Doug, Fred, Gene, Hope, Irene]    Ollie: weep outAll elements of queue: [Alice, Bob, Cindy, Doug, Fred, Gene, Hope, Irene, Kim, Lance, Mike, Nancy]    Fred: weep outAll elements of queue: [Gene, Hope, Irene, Kim, Lance, Mike, Nancy, Alice, Bob, Cindy, Doug]    Lance: weep outAll elements of queue: [Mike, Nancy, Alice, Bob, Cindy, Doug, Gene, Hope, Irene, Kim]    Cindy: weep outAll elements of queue: [Doug, Gene, Hope, Irene, Kim, Mike, Nancy, Alice, Bob]    Kim: weep outAll elements of queue: [Mike, Nancy, Alice, Bob, Doug, Gene, Hope, Irene]    Doug: weep outAll elements of queue: [Gene, Hope, Irene, Mike, Nancy, Alice, Bob]    Nancy: weep outAll elements of queue: [Alice, Bob, Gene, Hope, Irene, Mike]    Irene: weep outAll elements of queue: [Mike, Alice, Bob, Gene, Hope]    Hope: weep outAll elements of queue: [Mike, Alice, Bob, Gene]    Mike: weep outAll elements of queue: [Alice, Bob, Gene]    Bob: weep outAll elements of queue: [Gene, Alice]    Gene: weep outThe luck dog is: Alice

Reference: Data Structure and algorithm (Java description) by Deng Junhui
Please indicate the source for reprinting. Thank you!
Http://blog.csdn.net/github_27609763/article/details/46434301

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.