【发布时间】:2010-11-17 22:53:40
【问题描述】:
我必须在deque 上编写一小段代码,但是如果有人可以帮助我使用其中一种方法,我不确定如何编写这些方法的代码(例如。一种将对象添加到双端队列的方法)然后让我开始。我确信我可以管理其余的方法,只是目前我很困惑。
【问题讨论】:
-
你为什么要这样做?使用其中一种标准的 Deque 实现有什么问题?
我必须在deque 上编写一小段代码,但是如果有人可以帮助我使用其中一种方法,我不确定如何编写这些方法的代码(例如。一种将对象添加到双端队列的方法)然后让我开始。我确信我可以管理其余的方法,只是目前我很困惑。
【问题讨论】:
双端队列通常实现为双向链表。您可以通过跟踪列表中的第一个和最后一个元素并让每个元素跟踪其前任和后继来实现双向链表。
public class Deque<T> {
private class Node {
Node(T value) {
this.value = value;
}
T value;
Node next, prev;
}
private Node first, last;
public void addFront(T value) {
Node oldFirst = first;
first = new Node(value);
// The old first item is now the second item, so its the successor of
// the new first item
first.next = oldFirst;
// if first was null before, that means the deque was empty
// so first and last should both point to the new item
if(oldFirst == null) {
last = first;
} else {
// If there previously was a first element, this element is
// now the second element and its prev field should point to
// the new first item
oldFirst.prev = first;
}
}
}
【讨论】:
我不确定您到底在追求什么,但 Deque 的可用方法列在 Javadoc
【讨论】: