Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Queues {
- //queue from tail to head
- public static void main(String[] args) {
- }
- private class Node {
- int data;
- Node next;
- private Node(int data) {
- //node constructor
- this.data = data;
- }
- }
- private Node head;
- private Node tail;
- public void add(int elem) {
- //adds elem to queue (at tail)
- Node newNode = new Node(elem);
- if (tail == null) {
- tail = newNode;
- head = newNode;
- }
- else {
- newNode.next = tail;
- tail = newNode;
- }
- if (head == tail) head = newNode;
- }
- public int element() {
- //gets head of queue but doesn't remove it (similar to peek)
- return head.data;
- }
- public void offer(int elem) {
- //nice version of add
- add(elem); //nothing changes here because this is a linkedlist implementation
- }
- public int peek() {
- //returns head without deleting it
- return head.data;
- }
- public int poll() {
- //nice version of remove, returns null if elem doesn't exist (similar to pop)
- remove();
- }
- public int remove() {
- //removes element from head of queue and returns it (similar to pop)
- if (head == null) return -1;
- int temp = head.data;
- head = head.next;
- return temp;
- }
- public boolean isEmpty() {
- //returns true if queue is empty
- return (head == null);
- }
- public int size() {
- //returns size of queue
- int size = 0;
- Node current = tail;
- while (current != null) {
- size++;
- current = current.next;
- }
- return size;
- }
- public boolean find(int elem) {
- //returns true if elem exists in queue
- if (tail == null) return false;
- Node current = tail;
- while (current != null) {
- if (current.data == elem) return true;
- current = current.next;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement