Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. public class Queues {
  2.  
  3.     //queue from tail to head
  4.     public static void main(String[] args) {
  5.        
  6.     }
  7.  
  8.     private class Node {
  9.         int data;
  10.         Node next;
  11.         private Node(int data) {
  12.             //node constructor
  13.             this.data = data;
  14.         }
  15.     }
  16.  
  17.     private Node head;
  18.     private Node tail;
  19.  
  20.     public void add(int elem) {
  21.         //adds elem to queue (at tail)
  22.         Node newNode = new Node(elem);
  23.         if (tail == null) {
  24.             tail = newNode;
  25.             head = newNode;
  26.         }
  27.         else {
  28.             newNode.next = tail;
  29.             tail = newNode;
  30.         }
  31.         if (head == tail) head = newNode;
  32.     }
  33.  
  34.     public int element() {
  35.         //gets head of queue but doesn't remove it (similar to peek)
  36.         return head.data;
  37.     }
  38.  
  39.     public void offer(int elem) {
  40.         //nice version of add
  41.         add(elem); //nothing changes here because this is a linkedlist implementation
  42.     }
  43.  
  44.     public int peek() {
  45.         //returns head without deleting it
  46.         return head.data;
  47.     }
  48.  
  49.     public int poll() {
  50.         //nice version of remove, returns null if elem doesn't exist (similar to pop)
  51.         remove();
  52.     }
  53.  
  54.     public int remove() {
  55.         //removes element from head of queue and returns it (similar to pop)
  56.         if (head == null) return -1;
  57.         int temp = head.data;
  58.         head = head.next;
  59.         return temp;
  60.     }
  61.  
  62.     public boolean isEmpty() {
  63.         //returns true if queue is empty
  64.         return (head == null);
  65.     }
  66.  
  67.     public int size() {
  68.         //returns size of queue
  69.         int size = 0;
  70.         Node current = tail;
  71.         while (current != null) {
  72.             size++;
  73.             current = current.next;
  74.         }
  75.         return size;
  76.     }
  77.  
  78.     public boolean find(int elem) {
  79.         //returns true if elem exists in queue
  80.  
  81.         if (tail == null) return false;
  82.  
  83.         Node current = tail;
  84.         while (current != null) {
  85.             if (current.data == elem) return true;
  86.             current = current.next;
  87.         }
  88.         return false;
  89.  
  90.     }
  91.    
  92.  
  93.  
  94.    
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement