gpt4 book ai didi

java - 复制构造函数断言错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:43 24 4
gpt4 key购买 nike

由于断言错误,我的复制构造函数失败。据说队列的大小不正确,我不知道为什么。这是我的 Queue 类的代码:

public class Queue<T> implements UnboundedQueueInterface<T> {

public Node<T> head;
public Node<T> tail;
public int size = 0;

public Queue() {
// TODO 1

}

public Queue(Queue<T> other) {
// TODO 2
if(other.head==null){
this.head=null;}
else{
Node<T> newN = new Node<T>(other.head.data);
newN = other.head;
while(newN!=null){
T element = newN.data;
this.enqueue(element);
newN = newN.next;}
}

}

@Override
public boolean isEmpty() {
// TODO 3
return head==null;
}

@Override
public int size() {
// TODO 4
int sum = 0;
while(head!=null){
sum+=1;
head = head.next;
}
return sum;

}

@Override
public void enqueue(T element) {
// TODO 5
Node<T> newNode = new Node<T>(element, null);
if (isEmpty()) {head = newNode;} else {tail.next = newNode;}
tail = newNode;
this.size++;

}

@Override
public T dequeue() throws NoSuchElementException {
// TODO 6
if(isEmpty()){
throw new NoSuchElementException("empty queue");}
else{
T element = head.data;
if (tail == head) {
tail = null;
}
head = head.next;
this.size--;
return element;}

}

@Override
public T peek() throws NoSuchElementException {
// TODO 7
if(isEmpty()) throw new NoSuchElementException("empty queue");
else
return head.data;
}


@Override
public UnboundedQueueInterface<T> reversed() {
// TODO 8

Queue<T> output = new Queue<T>(this);
Node<T> node1 = new Node<T>(output.head.data);
node1 = output.head;
Node<T> node2 = new Node<T>(null); //nextNode
Node<T> node3 = new Node<T>(null); //prevNode

while(node1!=null){
node2 = node1.next;
node1.next = node3;
node3 = node1;
node1 = node2;
}
output.head = node3;
return output;

}



}

class Node<T> {
public T data;
public Node<T> next;
public Node(T data) { this.data=data;}
public Node(T data, Node<T> next) {
this.data = data; this.next=next;
}
}

这是测试代码:

public void testCopyConstructorEmptyNotAliased() throws Exception  {
Queue<Integer> q = new Queue<Integer>();
UnboundedQueueInterface<Integer> r;
r = new Queue<Integer>(q);
assertTrue(r.isEmpty());
assertTrue(q.isEmpty());

q.enqueue(1);
q.enqueue(2);
assertEquals(2, q.size());
assertTrue(r.isEmpty());

r.enqueue(3);
r.enqueue(4);
r.enqueue(5);
assertEquals(2, q.size());
assertEquals(3, r.size());

r.dequeue();
r.dequeue();
r.dequeue();
assertTrue(r.isEmpty());
assertEquals(2, q.size());

q.dequeue();
q.dequeue();
assertTrue(q.isEmpty());
}

最佳答案

您甚至不需要它迭代整个队列来查找队列的大小。因为在执行任何入队或出队操作时您已经在更新队列大小。您只需返回尺寸即可。

 @Override
public int size() {
// TODO 4
return this.size;
}

关于java - 复制构造函数断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011257/

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