![]() The generics in Java can be used to define a generic queue that can be used for any data type. If we want to have a queue that store double data, or some user-defined data, then this queue need to be changed and recompiled. But in the real world, the queue is not always used to store integers. The implementation of Queue, MyQueue looks good enough if we always want to store integers in the queue. Public int remove() throws QueueEmptyException Let us now change our remove function: class MyQueue This is the most basic implementation of a user-defined Exception in Java. Let us define an exception, QueueEmptyException as below: class QueueEmptyException extends Exception In the real world, we expect a queue to throw an exception when someone tries to remove the data from an empty queue. ![]() Let us say, our implementation will print this information and return -1 to indicate that queue was empty (it also means that -1 cannot be a valid value in the queue). Then remove function cannot remove anything from the list. What if the queue does not have any elements at all. Then we also set the rear pointer to NULL. If the list becomes empty after deleting the node (i.e there was only one node in the list). Similarly, remove function will remove the first node from the list and will return the value of that node. If the list was initially empty (i.e front was NULL), then it also set the front to point to the first (and only) node of the list. Insert function creates a new node with the given value and inserts that node at the end of the list (After rear node). Now, let us write the two main function, insert and remove, that insert (and remove) element from the queue in First-In-First-Out order. The check for Queue being empty or not is a simple check that checks the front (or rear) pointer. This can be set inside the constructor of MyQueue class class MyQueue This is just to facilitate the easy creation of Node. Note that we have added a constructor in the Node class. NODE OF THE LINKED LIST USED TO STORE QUEUE ELEMENTS The Queue class will have the following data structure front points to the first node in the list and rear point to the last node of the list. In the linked list implementation of the queue, we keep two pointers (references in Java) front and rear. In this post, we are going to give a similar implementation in Java.Īlso, we want to keep our implementation generic so that we can store any type of data in the Queue. We have already seen linked list implementation of Queue data structure in C++ earlier. Given the linked list implementation of a generic queue in Java.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |