Data structures 什么';这是一个基于单链表的数据结构,使得排队和退队都取O(1)?
一个结构是如何实现基于简单链表的抽象数据类型文件的,这样入队和出队过程都是O(1)? 约束:实现队列的结构必须仅由单个字段指向(例如:头、尾或元素数等) 我的理解是将单链表从头到尾循环 但即使在这种情况下,仍然需要两个指针:head和tail来满足O(1) 但是,问题要求队列只能由一个字段指向Data structures 什么';这是一个基于单链表的数据结构,使得排队和退队都取O(1)?,data-structures,Data Structures,一个结构是如何实现基于简单链表的抽象数据类型文件的,这样入队和出队过程都是O(1)? 约束:实现队列的结构必须仅由单个字段指向(例如:头、尾或元素数等) 我的理解是将单链表从头到尾循环 但即使在这种情况下,仍然需要两个指针:head和tail来满足O(1) 但是,问题要求队列只能由一个字段指向 有什么想法或提示吗?我认为这是可行的,你可以在循环链表中指向尾部,这样你就可以在O(1)中访问头部作为tail.next class Node<T> { T value; Node&l
有什么想法或提示吗?我认为这是可行的,你可以在循环链表中指向尾部,这样你就可以在O(1)中访问头部作为
tail.next
class Node<T> {
T value;
Node<T> next;
Node(T value, Node<T> next) { this.value = value; this.next = next; }
}
class Queue<T> {
Node<T> tail = null;
void enqueue(T t) {
if (tail == null) {
tail = new Node<T>(value, null);
tail.next = tail;
} else {
Node<T> newTail = new Node<T>(value, tail.next);
tail.next = newTail;
tail = newTail;
}
}
T dequeue() {
if (tail == null) throw new NoSuchElementException();
Node<T> head = tail.next;
T result = head.value;
if (head == tail) {
tail = null;
} else {
tail.next = head.next;
}
return result;
}
}
类节点{
T值;
节点下一步;
Node(T值,Node next){this.value=value;this.next=next;}
}
类队列{
节点尾=空;
无效排队(T){
if(tail==null){
tail=新节点(值,空);
tail.next=tail;
}否则{
Node newTail=新节点(值,tail.next);
tail.next=newTail;
尾=新尾;
}
}
T出列(){
如果(tail==null)抛出新的NoSuchElementException();
Node head=tail.next;
T结果=head.value;
如果(头=尾){
tail=null;
}否则{
tail.next=head.next;
}
返回结果;
}
}