LoganBlackisle

QueueLinkedList

Jun 17th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. package prep_28_queue;
  2.  
  3. public class QueueLinkedList {
  4. int key;
  5. QueueLinkedList next;
  6.  
  7. // constructor to create a new linked list node
  8. public QueueLinkedList(int key) {
  9. this.key = key;
  10. this.next = null;
  11. }
  12. }
  13.  
  14. // A class to represent a queue
  15. // The queue, front stores the front node of LL and rear stores the
  16. // last node of LL
  17. class Queue {
  18. QueueLinkedList front, rear;
  19.  
  20. public Queue() {
  21. this.front = this.rear = null;
  22. }
  23.  
  24. // Method to add an key to the queue.
  25. void enqueue(int key) {
  26.  
  27. // Create a new LL node
  28. QueueLinkedList temp = new QueueLinkedList(key);
  29.  
  30. // If queue is empty, then new node is front and rear both
  31. if (this.rear == null) {
  32. this.front = this.rear = temp;
  33. return;
  34. }
  35.  
  36. // Add the new node at the end of queue and change rear
  37. this.rear.next = temp;
  38. this.rear = temp;
  39. }
  40.  
  41. // Method to remove an key from queue.
  42. QueueLinkedList dequeue() {
  43. // If queue is empty, return NULL.
  44. if (this.front == null)
  45. return null;
  46.  
  47. // Store previous front and move front one node ahead
  48. QueueLinkedList temp = this.front;
  49. this.front = this.front.next;
  50.  
  51. // If front becomes NULL, then change rear also as NULL
  52. if (this.front == null)
  53. this.rear = null;
  54. return temp;
  55. }
  56.  
  57. // Driver class
  58. public static void main(String[] args) {
  59. Queue q = new Queue();
  60. q.enqueue(10);
  61. q.enqueue(20);
  62. q.dequeue();
  63. q.dequeue();
  64. q.enqueue(30);
  65. q.enqueue(40);
  66. q.enqueue(50);
  67.  
  68. System.out.println("Dequeued item is " + q.dequeue().key);
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment