Wednesday, May 25, 2016

MyQueue (FIFO): Implemented with Generics

MyQueue.java:

package com.lnn.ds.queue;

import java.util.Objects;

public class MyQueue<T> {
      private static class Node<T> {
            private Node<T> next;
            private T data;

            public Node(T data) {
                  this.data = data;
            }

            public T getData() {
                  return data;
            }

            public Node<T> getNext() {
                  return next;
            }

            public void setNext(Node<T> next) {
                  this.next = next;
            }

            public String toString() {
                  return String.valueOf(getData());
            }
      }

      private Node<T> head;

      private Node<T> tail;

      public boolean isEmpty() {
            return (head == null);
      }

      public boolean pop() {
            if (head != null) {
                  Node<T> tmp = head.getNext();
                  if (tmp == null) {
                        setTail(tmp);
                  }
                  setHead(tmp);
                  return true;
            }
            return false;
      }

      public void push(T data) {
            Node<T> next = new Node<T>(data);
            if (tail != null) {
                  tail.setNext(next);
            }
            setTail(next);
            if (head == null) {
                  setHead(next);
            }
      }

      public boolean search(T data) {
            Node<T> tmp = head;
            while (tmp != null) {
                  if (Objects.equals(tmp.getData(), data)) {
                        return true;
                  }
                  tmp = tmp.getNext();
            }
            return false;
      }

      private void setHead(Node<T> head) {
            this.head = head;
      }

      private void setTail(Node<T> tail) {
            this.tail = tail;
      }

      public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("[");
            Node<T> tmp = head;
            while (tmp != null) {
                  builder.append(tmp.getData());
                  tmp = tmp.getNext();
                  if (tmp != null) {
                        builder.append(", ");
                  }
            }
            builder.append("]");
            return builder.toString();
      }
}
MyQueueTest.java:

package com.lnn.ds.queue;

public class MyQueueTest {
      public static void main(String[] args) {
            MyQueue queue = new MyQueue();
            for (int i = 0; i < 10; i++) {
                  queue.push(i);
            }
            for(int i=0; i<10 span="">i++){
                  System.out.println(queue);
                  queue.pop();
            }
      }
}


No comments:

Post a Comment