gpt4 book ai didi

Java Deque 不使用任何现有的类(如 LinkedList)?

转载 作者:行者123 更新时间:2023-12-01 07:16:25 25 4
gpt4 key购买 nike

我必须在 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;
}
}
}

关于Java Deque 不使用任何现有的类(如 LinkedList)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1249022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com