我必须在deque
上编写一小段代码,但是我不知道如何编写方法的代码,如果有人可以帮助我使用其中一种方法,(例如,一个将对象添加到deque的对象的方法,那么这将使我开始。我确信我可以管理剩下的方法,就在我很难过的时候。
答案 0 :(得分:6)
Deques通常被实现为双向链表。您可以通过跟踪列表中的第一个和最后一个元素并让每个元素跟踪其前任和后继元素来实现双向链接列表。
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;
}
}
}
答案 1 :(得分:2)
我不确定你到底发生了什么,但是Javadoc
列出了Deque的可用方法