世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
public class TowList {
private Node first;
private Node last;
private Integer size = 0;
static class Node {
private Node pre;
private Node next;
private String value;
public Node (Node pre, String value, Node next) {
this.pre = pre;
this.value = value;
this.next = next;
}
}
public void addFirst (String value) {
Node f = first;
Node newNode = new Node(null, value, f);
first = newNode;
if (null == f) {
last = newNode;
} else {
f.pre = newNode;
}
size++;
}
public void addLast (String value) {
Node l = last;
Node newNode = new Node(l, value, null);
last = newNode;
if (l == null) {
first = newNode;
} else {
l.next = newNode;
}
size++;
}
public String removeFirst () {
Node f = first;
if (null == f) {
throw new NoSuchElementException();
}
Node next = f.next;
String value = f.value;
f.next = null;
f.value = null;
first = next;
if (null == next) {
last = null;
} else {
next.pre = null;
}
size--;
return value;
}
public String removeLast () {
Node l = last;
if (null == l) {
throw new NoSuchElementException();
}
Node pre = l.pre;
String value = l.value;
l.pre = null;
l.value = null;
last = pre;
if (null == pre) {
first = null;
} else {
pre.next = null;
}
size--;
return value;
}
public boolean hasNext () {
if (size > 0) {
return true;
}
return false;
}
public Integer size () {
return size;
}
public static void main(String[] args) {
TowList towList = new TowList();
towList.addLast("3");
towList.addLast("4");
towList.addLast("5");
System.out.println("size: " + towList.size());
// while (towList.hasNext()) {
// System.out.println(towList.removeFirst());
// }
while (towList.hasNext()) {
System.out.println(towList.removeLast());
}
}