Deque implementation
I implemented a generic Deque data structure.
Please, review this implementation
and The error doesnt make sense to me, plz info me a little bit
import java.util.NoSuchElementException;
import java.util.Iterator;
public class Deque<Item> implements Iterable<Item>
{
private int n;
private Node first;
private Node last;
private class Node
{
private Item item;
private Node next;
}
private class ListIterator implements Iterable<Item>
{
private Node<Item> current = first;
public boolean hasNext()
{
return current != null;
}
public Item next()
{
if(!hasNext())
{
throw new NoSuchElementException("Deque underflow");
}
Item item = current.item;
current = current.next;
return item;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
public Iterator<Item> iterator()
{
return new ListIterator();
}
public Deque()
{
n = 0;
first = null;
last = null;
}
// is the deque empty?
public boolean isEmpty()
{
return n ==0;
}
// return the number of items on the deque
public int size()
{
return n ;
}
// add the item to the front
public void addFirst(Item item)
{
if(item == null)
{
throw new IllegalArgumentException();
}
Node oldNode = first;
Node newNode = new Node();
newNode.item = item;
if(oldNode == null)
{
last = newNode;
}
else
{
newNode.next = oldNode;
}
first = newNode;
n++;
}
// add the item to the back
public void addLast(Item item)
{
if(item == null)
{
throw new IllegalArgumentException();
}
Node oldNode = last;
Node newNode = new Node();
newNode.item = item;
if(oldNode == null)
{
first = newNode;
}
else
{
oldNode.next = newNode;
}
last = newNode;
n++;
}
// remove and return the item from the front
public Item removeFirst()
{
if(isEmpty())
{
throw new NoSuchElementException("Deque underflow");
}
Item item = first.item;
first = first.next;
n--;
if(isEmpty())
{
first=null;
}
return item;
}
// remove and return the item from the back
public Item removeLast()
{
if(isEmpty())
{
throw new NoSuchElementException("Deque underflow");
}
Node secondLast = first;
if(n>3)
{
while(secondLast.next.next != null)
{
secondLast = secondLast.next;
}
}
else
{
secondLast = first;
}
Item item = last.item;
last = secondLast;
n--;
if(isEmpty())
{
last = null;
}
return item;
}
}
Test file
import java.util.Iterator;
public class dequeTest
{
public static void main(String[] args)
{
Deque<Double> d = new Deque<Double>();
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
d.addFirst(2.0);
System.out.println(d.removeFirst());
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
d.addFirst(1.2);
System.out.println(d.removeLast());
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
d.addLast(1.4);
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
for(int i = 0;i<10;i++)
{
d.addLast((double)i);
}
for(double value: d)
{
System.out.print(value);
}
}
}
Error
Type mismatch: cannot convert from Deque.ListIterator to Iterator
Can anyone help with the error? and fix it if you have a better idea
An Iterable<T> is not an Iterator<T>, but it has a method to get an Iterator<T>. Just change
public Iterator<Item> iterator()
{
return new ListIterator();
}
to
public Iterator<Item> iterator()
{
return new ListIterator().iterator();
}
beyond that, I would suggest you use an ArrayDeque (or even LinkedList) when you need a Deque. Your implementation does not appear to improve on either and worse your class name shadows the java.util.Deque interface (which you don't implement). Finally, a Deque should be a Collection (not just Iterable).
Related
I am trying to make a double ended deque but I keep running into errors I frankly have no idea how to solve. The first one is regarding deque. In my iterator function, I keep getting the following error and I have no idea why:
Deque.java:105: error: incompatible types: Deque.DequeIterator cannot be converted to Iterator<Item>
return new DequeIterator();
Additionally, I have been trying to throw exceptions but haven't been able to for some reason. I keep getting errors such as the following:
Deque.java:72: error: cannot find symbol
throw java.util.NoSuchElementException();
^
symbol: class util
location: package java
Here is my code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item>{
private int size;
private Node<Item> first;
private Node<Item> last;
private class Node<Item>{
Item item;
Node<Item> next;
Node<Item> prev;
Node(Item item) {
this.item = item;
next = null;
prev = null;
}
}
// construct an empty deque
public Deque(){
first = null;
last = null;
size = 0;
}
public boolean isEmpty(){return size == 0;} // is the deque empty?
public int size(){return size;} // return the number of items on the deque
// add the item to the front
public void addFirst(Item item){
if (item == null){
throw new java.lang.NullPointerException();
}
else if (this.isEmpty()){
first = new Node(item);
first = last;
}
else{
Node oldfirst = first;
Node first = new Node(item);
first.next = oldfirst;
oldfirst.prev = first;
}
size ++;
}
// add the item to the end
public void addLast(Item item){
if (item == null){
throw new java.lang.NullPointerException();
}
else if (this.isEmpty()){
Node last = new Node(item);
last = first;
}
else{
Node oldlast = last;
Node last = new Node(item);
oldlast.next = last;
last.prev = oldlast;
}
size ++;
}
// remove and return the item from the front
public Item removeFirst(){
if (this.isEmpty()){
throw java.util.NoSuchElementException();
}
else{
Item item = first.item;
first = first.next;
first.prev = null;
if (size == 1){
first = last;
}
size --;
return item;
}
}
// remove and return the item from the end
public Item removeLast(){
if (this.isEmpty()){
throw java.util.NoSuchElementException();
}
else{
Item item = last.item;
last = last.prev;
if (size == 1){
last = first;
}
size --;
return item;
}
}
// return an iterator over items in order from front to end
public Iterator<Item> iterator() {
return new DequeIterator();
}
private class DequeIterator<Item> implements Iterable<Item>{
private Node current;
public DequeIterator() { this.current = first;}
public boolean hasNext(){ return current != null;};
public void remove() {throw new UnsupportedOperationException();}
public Item next(){
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
// unit testing (optional)
public static void main(String[] args){
Deque<String> deque = new Deque<String>();
deque.addFirst("1");
//StdOut.println("addfirst to string: " + deque.AXCToString());
deque.addFirst("2");
//StdOut.println("addfirst to string: " + deque.AXCToString());
deque.addFirst("3");
//StdOut.println("addfirst to string: " + deque.AXCToString());
deque.addFirst("4");
//StdOut.println("addfirst to string: " + deque.AXCToString());
deque.addFirst("5");
}
}
Your first issue is that your DequeIterator class implements Iterable, when it should implement Iterator. Iterable is usually used for things like collections, which can then provide an Iterator instance. It looks like you've already implemented the methods for Iterator, so this should just be a matter of changing the line to be:
private class DequeIterator<Item> implements Iterator<Item> {
For your second issue, you're missing the new keyword to construct the exception. It should be as follows:
throw new java.util.NoSuchElementException();
Additionally, it's standard practice in Java to use imports rather than using absolute paths, and it looks like you've already imported it, so you can shorten it to just this:
throw new NoSuchElementException();
I'm wondering if this has something to do with how I specified my Singly Linked List class, but the problem is eluding me.
Here is the Singly Linked List class:
class SLList {
private static Node head;
private static long size;
public SLList() {
head = new Node(null, null);
setSize(0);
}
static class Node {
private Object data;
private Node next;
public Node(Object newData, Node n) {
data = newData;
next = n;
}
public Node getNext() {
return next;
}
public void setElement(Object element) {
data = element;
}
public void setNext(Node newNext) {
next = newNext;
}
public String toString() {
String result = data + " ";
return result;
}
public Object getObject() {
return data;
}
}
public Node getHead() {
return head;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public void addLast(Object object) {
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = new Node(object, null);
size++;
}
public void remove(Object object) {
Node pre = head;
Node temp = head.next;
while(temp.next != null) {
pre = temp;
temp = temp.next;
if(temp.data.equals(object)) {
pre = temp.next;
temp = temp.next.next;
size--;
}
}
}
public void printElements() {
Node temp = head;
if(temp.next == null) {
System.out.println("List is empty.");
}
else {
while(temp.next != null) {
temp = temp.next;
System.out.println(temp.data);
}
}
}
}
This is the Set class with a method to add new values to the lists, barring duplicates already in the list:
public class Set {
SLinkedList aList;
SLinkedList bList;
SLinkedList cList;
SLinkedList dList;
public Set() {
aList = new SLinkedList();
bList = new SLinkedList();
cList = new SLinkedList();
dList = new SLinkedList();
}
public SLinkedList getList(char x) {
if(x == 'a') {
return aList;
}
else if(x == 'b') {
return bList;
}
else if(x == 'c') {
return cList;
}
else {
return dList;
}
}
public boolean addElement(SLinkedList list, Object newData) {
SLinkedList.Node newNode = new SLinkedList.Node(newData, null);
SLinkedList.Node traverseNode = list.getHead();
while(traverseNode.getNext() != null) {
traverseNode = traverseNode.getNext();
if(traverseNode.getObject().equals(newNode.getObject())) {
System.out.println("This data is already in the list.");
return false;
}
}
list.addLast(newData);
System.out.println("Node added!");
return true;
}
public void fillList() {
aList.addLast("dog");
aList.addLast(4);
bList.addLast("test");
System.out.println("aList: ");
aList.printElements();
System.out.println("bList: ");
bList.printElements();
}
}
This is the output when I try to use fillList() to add values to the first Singly Linked List, aList
aList:
dog 4 test
bList:
dog 4 test
As you can see, adding values to aList adds the same values to bList. Any help would be greatly appreciated!
This:
private static Node head;
means you have one head for all your instances of SLLIst. So all SLList instance share the same head.
This should be a member of your class, and as such you'll have an instance of head per instance of SLLIst.
e.g.
private Node head;
The same applies to your size field. I don't think you'll need any static members.
Alright, so I hate to ask for help on a problem so vague, but I'm working on a project right now that doesn't seem to be getting any compile-time errors, yet won't do what's asked of it. To sum it up simply, this project is a linked list(unordered list, to be specific) that functions as a text editor. It takes in a file as a command line argument, then stores every separate line of the document as a node in the list. Whether it's doing that for sure or not I don't know, but after that the program takes in specific commands(keyboard input) and edits or lists the text of the file as requested.
The problem is, I can't even tell if the file is being stored in the list or not because every time I give the command L for list, the program just 'skips' it and continues on as if nothing was asked of it. It may be that the file isn't being stored for whatever reason, or there may be an issue with the toString method of the unorderedList class.
The code for all of my classes is as follows:
public class LinearNode<T> {
//Begin by declaring the basic node and its data
private LinearNode<T> next;
private T element;
public LinearNode() {
//The basic null constructor
next = null;
element = null;
}
public LinearNode(T elem) {
//The overloaded constructor to create a node
next = null;
element = elem;
}
public LinearNode<T> getNext() {
//Get the node reference
return next;
}
public void setNext(LinearNode<T> node) {
//Create or redirect a node reference
next = node;
}
public T getElement() {
//Get the actual data stored in the node
return element;
}
public void setElement(T elem) {
//Create or redirect the node's data
element = elem;
}
}
And for the lists
public abstract class LinkedList<T> implements ListADT<T>, UnorderedListADT<T> {
protected int count;
protected LinearNode<T> head, tail;
protected int modCount;
public LinkedList () {
count = 0;
head = null;
tail = null;
head = tail;
head.setNext(tail);
modCount = 0;
}
public T remove(T targetElement) throws EmptyCollectionException, ElementNotFoundException {
if(isEmpty())
throw new EmptyCollectionException("LinkedList");
boolean found = false;
LinearNode<T> previous = null;
LinearNode<T> current = head;
while(current!=null&&!found) {
if(targetElement.equals(current.getElement())) {
found = true;
}
else {
previous = current;
current = current.getNext();
}
}
if(!found)
throw new ElementNotFoundException("Linked List");
if(size()==1) {
head = tail = null;
}
else if(current.equals(head))
head = current.getNext();
else if(current.equals(tail)) {
tail = previous;
tail.setNext(null);
}
else {
previous.setNext(current.getNext());
}
count--;
modCount++;
return current.getElement();
}
}
import java.util.Iterator;
public class UnorderedList<T> extends LinkedList<T>{
public UnorderedList() {
super();
}
public void addToFront(T element) {
if(head==null) {
head = new LinearNode<T>(element);
if(tail==null) {
tail = head;
}
count++;
modCount++;
}
else {
LinearNode<T> current = head;
head.setElement(element);
head.setNext(current);
count++;
modCount++;
}
}
public void addToRear(T element) {
if(tail.getElement()==null) {
tail.setElement(element);
count++;
modCount++;
}
else {
LinearNode<T> current = tail;
tail = new LinearNode<T>(element);
current.setNext(tail);
count++;
modCount++;
}
}
public void addAfter(T element, T target) {
LinearNode<T> current = head;
LinearNode<T> node = new LinearNode<T>(element);
LinearNode<T> temp = null;
while(!(current.getElement()==target)) {
current = current.getNext();
}
if(!(current.getNext()==null)) {
temp = current.getNext();
//temp.setElement(current.getElement());
}
current.setNext(node);
node.setNext(temp);
count++;
modCount++;
}
public T removeLast() {
T last = tail.getElement();
tail = null;
LinearNode<T> current = head;
while(!(current.getNext()==null)) {
current = current.getNext();
}
current = tail;
count--;
modCount++;
return last;
}
public int size() {
return count;
}
public Iterator<T> iterator() {
Iterator<T> itr = this.iterator();
return itr;
}
public boolean isEmpty() {
boolean result = false;
if(head==null&&tail==null) {
result = true;
}
else
result = false;
return result;
}
public T first() {
return head.getElement();
}
public T last() {
return tail.getElement();
}
public boolean contains(T elem) {
boolean result = false;
for(T element : this) {
if(element==elem) {
result = true;
break;
}
}
return result;
}
public T removeFirst() {
LinearNode<T> current = head;
head = current.getNext();
count--;
modCount++;
return current.getElement();
}
public String toString() {
LinearNode<T> current = head;
String s = "";
for(int countA=0;countA<count;count++) {
s += (countA+1)+"> "+current.getElement()+"\n";
current = current.getNext();
}
return s;
}
}
and for the main editor
import java.util.Scanner;
import java.util.Iterator;
import java.io.*;
public class myEditor {
public static void saveToFile(String text, String filename) throws IOException{
PrintWriter out = new PrintWriter(new File(filename));
out.println(text);
out.close();
}
public static void main(String args[]) {
boolean quit = false;
try {
if(args.length!=1) {
throw new IllegalArgumentException();
}
String filename = args[0];
Scanner input = new Scanner(new File(filename));
//Add exception
UnorderedList<String> list = new UnorderedList<String>();
while(input.hasNextLine()) {
if(list.head==null) {
list.addToFront(input.nextLine());
}
list.addToRear(input.nextLine());
}
System.out.println(">");
do {
Scanner command = new Scanner(System.in);
String comm = command.next();
String[] comm1 = comm.split(" ");
if(comm1.length==1) {
if(comm1[0].equalsIgnoreCase("I")) {
System.out.println("Type a line of text >");
comm = command.next();
list.addToRear(comm);
}
else if(comm1[0].equalsIgnoreCase("L")) {
System.out.print(list.toString());
}
else if(comm1[0].equalsIgnoreCase("E")) {
saveToFile(list.toString(), filename);
quit = true;
break;
}
}
else {
if(comm1[0].equalsIgnoreCase("I")) {
int linNum = Integer.parseInt(comm1[1]);
Iterator<String> itr = list.iterator();
String current = "";
for(int count=0;count<linNum;count++) {
current = itr.next();
}
list.addAfter(comm, current);
}
else if(comm1[0].equalsIgnoreCase("D")) {
int linNum = Integer.parseInt(comm1[1]);
if(linNum<=list.count&&linNum>0) {
Iterator<String> itr = list.iterator();
String current = "";
for(int count=0;count<linNum;count++) {
current = itr.next();
}
list.remove(current);
}
}
}
}
while(!quit);
}
catch(IllegalArgumentException e) {
System.err.print(e.getMessage());
}
catch(FileNotFoundException e) {
System.err.print(e.getMessage());
}
catch(IOException e) {
System.err.print(e.getMessage());
}
}
}
There's a few other classes and some interfaces as well, but for the issue I'm experiencing, I don't think they're that relevant.
Does anyone see what might be happening here, or what I might have written wrong to cause my program to ignore the command?
Look at your LinkedList constructor
head = null;
tail = null;
head = tail;
head.setNext(tail);
head is null yet you call its setNext method, it should throw an NPE.
I've looked at a bunch of the questions in this area and can't find one that solves my problem specifically.
Basically, this is a homework assigment where I have a linked list with nodes, which hold an element. The node class (LinearNode) and the element class (Golfer) both implement Comparable and override the compareTo method. However, the runtime fails trying to add a new node to the list (first node is added fine) with a class cast exception: supersenior.LinearNode cannot be cast to supersenior.Golfer. I don't know why it's trying to take the node and compare it to an element of the node to be compared...i've even tried explicitly casting. The following error is observed:
Exception in thread "main" java.lang.ClassCastException: supersenior.LinearNode cannot be cast to supersenior.Golfer
at supersenior.Golfer.compareTo(Golfer.java:12)
at supersenior.LinearNode.compareTo(LinearNode.java:80)
at supersenior.LinearNode.compareTo(LinearNode.java:80)
at supersenior.LinkedList.add(LinkedList.java:254)
at supersenior.SuperSenior.main(SuperSenior.java:100)
Any help would be greatly appreciated. Thanks!
LinkedList class:
package supersenior;
import supersenior.exceptions.*;
import java.util.*;
public class LinkedList<T> implements OrderedListADT<T>, Iterable<T>
{
protected int count;
protected LinearNode<T> head, tail;
/**
* Creates an empty list.
*/
public LinkedList()
{
count = 0;
head = tail = null;
}
public T removeFirst() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
LinearNode<T> result = head;
head = head.getNext();
if (head == null)
tail = null;
count--;
return result.getElement();
}
public T removeLast() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
LinearNode<T> previous = null;
LinearNode<T> current = head;
while (current.getNext() != null)
{
previous = current;
current = current.getNext();
}
LinearNode<T> result = tail;
tail = previous;
if (tail == null)
head = null;
else
tail.setNext(null);
count--;
return result.getElement();
}
public T remove (T targetElement) throws EmptyCollectionException,
ElementNotFoundException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
boolean found = false;
LinearNode<T> previous = null;
LinearNode<T> current = head;
while (current != null && !found)
if (targetElement.equals (current.getElement()))
found = true;
else
{
previous = current;
current = current.getNext();
}
if (!found)
throw new ElementNotFoundException ("List");
if (size() == 1)
head = tail = null;
else if (current.equals (head))
head = current.getNext();
else if (current.equals (tail))
{
tail = previous;
tail.setNext(null);
}
else
previous.setNext(current.getNext());
count--;
return current.getElement();
}
public boolean contains (T targetElement) throws
EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
boolean found = false;
Object result;
LinearNode<T> current = head;
while (current != null && !found)
if (targetElement.equals (current.getElement()))
found = true;
else
current = current.getNext();
return found;
}
public boolean isEmpty()
{
return (count == 0);
}
public int size()
{
return count;
}
public String toString()
{
LinearNode<T> current = head;
String result = "";
while (current != null)
{
result = result + (current.getElement()).toString() + "\n";
current = current.getNext();
}
return result;
}
public Iterator<T> iterator()
{
return new LinkedIterator<T>(head, count);
}
public T first()
{
return head.getElement();
}
public T last()
{
return tail.getElement();
}
#Override
public void add (T element)
{
LinearNode<T>node = new LinearNode<T>();
node.setElement(element);
if(isEmpty())
{
head = node;
if(tail == null)
tail = head;
//node.setNext(head);
//head.setPrevious(node);
//head.setElement((T) node);
count++;
}
else
{
for(LinearNode<T> current = head; current.getNext() != null; current = current.getNext())
if(node.compareTo((T) current) >= 0)
{
current.setPrevious(current);
current.setNext(current);
}
else
{
current.setPrevious(node);
}
tail.setNext(node);
}
}
}
LinearNode class:
package supersenior;
public class LinearNode<E> implements Comparable<E>
{
private LinearNode<E> next, previous;
public E element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode (E elem)
{
next = null;
element = elem;
}
public LinearNode<E> getNext()
{
return next;
}
public void setNext (LinearNode<E> node)
{
next = node;
}
public E getElement()
{
return element;
}
public void setElement (E elem)
{
element = elem;
}
#Override
public int compareTo(E otherElement) {
return ((Comparable<E>) this.element).compareTo(otherElement);
}
public LinearNode<E> getPrevious()
{
return previous;
}
public void setPrevious (LinearNode<E> node)
{
previous = node;
}
}
The element class (Golfer):
package supersenior;
public class Golfer implements Comparable<Golfer>{
Golfer imaGolfer;
String name;
int tourneys;
int winnings;
double avg;
public Golfer(String attr[]){
this.name = attr[0];
this.tourneys = Integer.parseInt(attr[1]);
this.winnings = Integer.parseInt(attr[2]);
this.avg = findAvg(winnings, tourneys);
}
private double findAvg(int winnings, int tourneys){
double a = winnings/tourneys;
return a;
}
#Override
public String toString(){
return "Name: " + name + " Tourneys: " + tourneys + " Winnings: " + winnings + " Average: " + avg;
}
#Override
public int compareTo(Golfer golfer) {
if(this.avg <= golfer.avg)
return 1;
if(this.avg == golfer.avg)
return 0;
else
return -1;
}
}
The problem is that you're mixing what's being compared. You're trying to compare the LinearNode object (which holds an E) to an actual E. LinearNode<E> shouldn't implement Comparable<E>; if anything, it might implement Comparable<LinearNode<E>>, and the type parameter should probably be E extends Comparable<E>.
If you want to order LinearNodes based on the ordering of their underlying elements, you should use something like this:
// in LinearNode
public int compareTo(LinearNode<E> otherNode) {
return this.element.compareTo(otherNode.element);
}
(Note that the Java sorted collections don't require elements to implement Comparable, since you can provide a custom Comparator for any of them, but in the case of this assignment it's probably fine to require that E extends Comparable<E>.)
(Note 2: If you're using Generics, any cast, such as your (Comparable<E>), is a red flag; the purpose of the Generics system is to eliminate the need for most explicit casts.)
I am trying to implement a Deque in java using linked list. As a start I want to implement the method addFirst(). Here is the problem I am getting -- when I add few Strings, for example, "one", "two" and "three", it is inserting correctly, but when iterating the deque, it is only giving the last added object, not all the objects. Is there anything I am missing?
public class Deque<Item> implements Iterable<Item> {
private Node first;
private Node last;
private int N;
public Iterator<Item> iterator() { return new DequeIterator(); }
private class Node {
private Item item;
private Node next;
}
public Deque() {
first = null;
last = null;
N = 0;
}
public boolean isEmpty() { return first == null || last == null; }
public int size() { return N; }
public void addFirst(Item item) {
if (null == item) { throw new NullPointerException("Can not add a null value"); }
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = null;
if (isEmpty()) {
last = first;
} else {
oldFirst.next = first;
}
N++;
}
private class DequeIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) { throw new NoSuchElementException(); }
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String args[]) {
Deque<String> deque = new Deque<String>();
deque.addFirst("one");
deque.addFirst("two");
deque.addFirst("three");
deque.addFirst("four");
for (String s : deque) {
System.out.println(s); // prints only "four"
}
}
}
Change oldFirst.next = first to first.next = oldFirst in addFirst() and it should work.
Right now first.next after addFirst() call isn't pointing to anything, as you're setting it to null. This causes the hasNext() method to return false, resulting in invalid iteration.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Deque.Node first;
private Deque.Node last;
private int N;
public Iterator<Item> iterator() {
return new Deque.DequeIterator();
}
private class Node {
private Item item;
private Deque.Node next;
}
public Deque() {
first = null;
last = null;
N = 0;
}
public boolean isEmpty() {
return first == null || last == null;
}
public int size() {
return N;
}
public void addFirst(Item item) {
if (null == item) {
throw new NullPointerException("Can not add a null value");
}
if (first == null && last == null) {
first = new Node();
first.item = item;
first.next = null;
last = first;
} else {
Node node = new Node();
node.item = item;
node.next = first;
first = node;
}
N++;
}
private class DequeIterator implements Iterator<Item> {
private Deque.Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Item item = (Item) current.item;
current = current.next;
return item;
}
}
public static void main(String args[]) {
Deque<String> deque = new Deque<String>();
deque.addFirst("one");
deque.addFirst("two");
deque.addFirst("three");
deque.addFirst("four");
for (String s : deque) {
System.out.println(s); // prints only "four"
}
}
}
output :
four
three
two
one