即時解決一些實踐的東西,爲我的測試。我的課本中的問題要求我反向打印圓形鏈表中的內容。所以我的想法是創建一個堆棧,將這些東西移動到堆棧然後彈出。從圓形鏈表創建一個堆棧,以便反向打印列表
這裏是我做了什麼:
public void reversePrint() {
Stack stack = new Stack();
Node<E> temp = list;
do {
stack.push(temp);
temp = temp.getNext();
} while (temp != list);
while (!stack.empty()) {
System.out.print(stack.pop());
}
}
circularlist.java
public class CircularList<E> implements List<E> {
Node<E> list;
int size;
public CircularList() {
list = new Node(null);
list.setNext(list);
size = 0;
}
@Override
public void add(E element) {
Node<E> newNode = new Node(element);
newNode.setNext(list.getNext());
list.setNext(newNode);
size++;
}
@Override
public boolean remove(E element) {
Node<E> location = find(element);
if (location != null) {
location.setNext(location.getNext().getNext());
size--;
}
return location != null;
}
@Override
public E get(E element) {
Node<E> location = find(element);
if (location != null) {
return (E) location.getNext().getInfo();
}
return null;
}
@Override
public boolean contains(E element) {
return find(element) != null;
}
@Override
public int size() {
return size;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
Node<E> tmp = list.getNext();
@Override
public boolean hasNext() {
return tmp != list;
}
@Override
public E next() {
E info = tmp.getInfo();
tmp = tmp.getNext();
return info;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
protected Node<E> find(E element) {
Node<E> tmp = list;
while (tmp.getNext() != list && !tmp.getNext().getInfo().equals(element)) {
tmp = tmp.getNext();
}
if (tmp.getNext() == list) {
return null;
} else {
return tmp;
}
}
Node.java
public class Node<E> {
E info;
Node<E> next;
public Node(E element) {
info = element;
next = null;
}
public void setInfo(E element) {
info = element;
}
public E getInfo() {
return info;
}
public void setNext(Node<E> next) {
this.next = next;
}
public Node<E> getNext() {
return next;
}
}
我的問題是我不能使用做。我需要一個不同的解決方案。任何幫助?
*爲什麼*你不能使用'do'? – 2013-05-11 08:36:13
不知何故,你需要迭代你的列表中的節點......你有什麼要求/需要使用,然後如果不是'做'?順便說一句...你有'節點'getPrevious()'方法? – A4L 2013-05-11 08:38:36
@ A4L不,它是一個單一的循環鏈表,但是我有一個只用next和hasNext方法設計的迭代器。 – user2272227 2013-05-11 09:05:01