问题描述
我使用链接列表直接实现了堆栈,但是在测试代码期间,我注意到实例变量first
不会保留状态,并且在后续的推入操作期间会恢复为NULL。当N保留其值时,变量first
不会。有人可以帮忙吗?
import java.util.NoSuchElementException;
public class Stack <T> {
private Node first;
private Node current;
private int N;
private class Node {
T item;
Node next;
}
public void push(T item) {
Node oldFirst = first;
Node first = new Node();
first.item = item;
first.next = oldFirst;
N++;
}
public T pop() throws NoSuchElementException{
try {
T item = first.item;
first = first.next;
N--;
return item;
} catch (java.lang.NullPointerException error) {
throw new NoSuchElementException("Stack is empty.");
}
}
}
测试客户端:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class TestStack {
/**
* Test the LIFO property of the stack i.e. the item pushed last into the
* stack is the one to be popped first from the stack.
*/
@Test
void testLIFOPropertyWithIntegerStack() {
int[] testClient = new int[] {1,2,3,4,5,6,7,8,9,10};
Stack<Integer> stack = new Stack<> ();
for (int item : testClient) {
stack.push(item);
}
int index = testClient.length - 1;
while (stack.size() != 0) {
int item = stack.pop();
assertEquals(item,testClient[index--]);
}
}
}
解决方法
您的push方法存在问题。您的Node first = new Node();
在堆栈中隐藏了字段first
。
因此,更改:
Node first = new Node();
到
// This is your object field
first = new Node();
测试将通过。请记住,由于您的测试方法使用size()
,因此需要实现它。
public int size(){
return N;
}