【JAVA数据结构】带dummy节点的双向队列

来源:互联网 发布:c语言学习班 编辑:程序博客网 时间:2024/06/06 06:48
package dequeue;import java.util.Iterator;public class Deque<Item> implements Iterable<Item> {public class Node{Item value = null;Node next = null;Node prev = null;}publicclass terminal extends Node{private int cp;terminal(int cp){this.cp = cp;}}public terminal head = new terminal(-1);public terminal tail = new terminal(-1);private int size;public Deque(){head.next = tail;tail.prev = head;size = 0;}public boolean isEmpty() {return size == 0 ;}public int size()  {return size;}public void addFirst(Item item)  {Node tmp = new Node();tmp.value = item;tmp.prev = head;tmp.next = head.next;head.next = tmp;size++;}public void addLast(Item item){// add the item to the endNode tmp = new Node();tmp.value = item;tmp.prev = tail.prev;tail.prev.next = tmp;tmp.next = tail;tail.prev = tmp;size++;}public Item removeFirst(){// remove and return the item from the frontif(size==0){throw new java.util.NoSuchElementException();}Item result = head.next.value;head.next = head.next.next;size--;return result;}public Item removeLast(){// remove and return the item from the endif(size==0){throw new java.util.NoSuchElementException();}Item result = tail.prev.value;Node tmp = tail.prev;tail.prev = tmp.prev;tmp.prev.next = tail;tmp = null;size--;return result;}public Iterator<Item> iterator(){return new DequeIterator();}private class DequeIterator implements Iterator<Item> {private Node currentNode = head.next;@Overridepublic boolean hasNext() {// TODO Auto-generated method stubreturn currentNode != tail;}@Overridepublic Item next() {// TODO Auto-generated method stubif (!hasNext()) throw new java.util.NoSuchElementException();Item item = currentNode.value;currentNode = currentNode.next;return item;}}}

0 0