Monday, March 20, 2017

Implement Queue with doubly linked list

public class MyQueue<T> {
private ListNode<T> head;
private ListNode<T> tail;
private int length;
public MyQueue<T> {
this.head = null;
this.tail = null;
this.length = 0;
}
public void offer(T element) {
ListNode<T> newNode = new ListNode<T>(element);
if (tail == null) {
head = newNode;
tail = newNode;
}
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
length++;
}
public T poll() {
if (head == null) return null;
ListNode temp = head;
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = null;
temp.next = null;
}
length--;
return temp.item;
}
public T peek() {
if (head == null) return null;
return head.item;
}
}

No comments:

Post a Comment