这可能是构建链表的更简单方法之一:
String map = "ABBACBCCA";
ListNode<Character> head = null;
ListNode<Character> tail = null;
for (char c:map.toCharArray()) {
final ListNode<Character> node = new ListNode<>(c);
if (head == null) {
head = node;
} else {
tail.next = node;
}
tail = node;
}
同时照顾你的类型参数无处不在
class ListNode<T> {
public T data = null;
ListNode<T> next = null;
public ListNode(T data) {
this.data = data;
}
}
更不用说您也可以充分利用Java api:
LinkedList<Character> ll =
"ABBACBCCA".chars()
.mapToObj(i->(char)i) // takes care of boxing char
.collect(Collectors.toCollection(LinkedList<Character>::new));
另外要遍历你ListNode
的,你可以考虑添加:
class ListNodeIterator<T> implements Iterator<T> {
private ListNode<T> current;
public ListNodeIterator<T> ListNodeIterator(ListNode<T> node) {
current = node;
}
public boolean hasNext() {
return current.next != null;
}
public T next() {
current = current.next;
return current.data;
}
}
通过以下修改:
class ListNode<T> implements Iterable<T> {
public T data = null;
public ListNode<T> next = null;
public ListNode(T data) {
this.data = data;
}
public Iterator<T> iterator() {
return new ListNodeIterator<>(this);
}
}
因此,您可以按如下方式使用它:
for (char c:head) {
System.out.println("Character: "+c);
}
甚至
head.forEach(c->{System.out.println("Character: "+c);});
嗯……这不是一次愉快的爪哇之旅吗?