【发布时间】:2013-05-11 08:30:52
【问题描述】:
我正在为我的测试解决一些练习问题。我教科书中的问题要求我将循环链表中的内容反向打印。所以我的想法是创建一个堆栈,将内容移动到堆栈然后弹出它。
这是我所做的:
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());
}
}
循环列表.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。我需要一个不同的解决方案。有什么帮助吗?
【问题讨论】:
-
为什么不能使用
do? -
您需要以某种方式遍历列表的节点...如果不是
do,那么您允许/需要使用什么?顺便说一句...Node中有getPrevious()方法吗? -
@A4L 不,它是一个单循环链表,但我设计了一个迭代器,仅使用 next 和 hasNext 方法。
-
@JonSkeet 在我练习的课程中还没有参加。
-
@user2272227:
do是一个循环 - 但由于某种原因你不能使用它。break是循环的一部分,但你不能使用它。所以你的评论并没有说明你可以使用什么。
标签: java linked-list stack