If you use Java 8+, StringJoiner simplified.
@Override public String toString() { StringJoiner joiner = new StringJoiner("<-->", "head-->", "<--tail"); for (IntegerNode node = this.head; node != null; node = node.getNext()) joiner.add(String.valueOf(node.getData())); return joiner.toString(); }
If you are not using Java 8, StringBuilder is the right way.
(Runs better than directly using String )
@Override public String toString() { StringBuilder buf = new StringBuilder("head-->"); boolean sep = false; for (IntegerNode node = this.head; node != null; node = node.getNext()) { if (sep) buf.append("<-->"); buf.append(node.getData()); sep = true; } return buf.append("<--tail").toString(); }
In both cases, you use the base for loop with the node variable to iterate through the list.
As for the rest of your code, you have some problems.
public IntegerNode(int data){ next = next; prev = prev; data = data; }
The purpose of next - next and prev - prev does not make sense.
Assigning a parameter to a field will only work if you assign the field using this. otherwise, you assign the parameter to yourself (meaningless).
public IntegerNode(int data){ this.data = data; }
public int getData(){ data = data; return this.data; }
Assigning data to data pointless.
public int getData(){ return this.data; }
public void setNext(IntegerNode in){ prev = in; }
Copy / paste the error. You assigned next .
public void setNext(IntegerNode in){ next = in; }
public int pollFirst(){ int x = head.getData(); head = head.getNext(); head.setPrevious(null); return x; } public int pollLast(){ int x = tail.getData(); tail = tail.getPrevious(); tail.setNext(null); return x; }
These methods will throw a NullPointerException when polling the last value 1 from the list.
Add the missing if .
public int pollFirst(){ int x = head.getData(); head = head.getNext(); if (head == null) tail = null; else head.setPrevious(null); return x; } public int pollLast(){ int x = tail.getData(); tail = tail.getPrevious(); if (tail == null) head = null; else tail.setNext(null); return x; }
1) "last" means "only the remaining" value, not the "tail" value.