I have a straightforward implementation of stack, using Linked Lists, however during testing the code I noticed that the instance variable first
does not retain state and gets reverted to NULL during subsequent push operations. While N retains its values, the variable first
does not. Can someone please help?
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.");
}
}
}
Test Client:
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--]);
}
}
}
There is a problem in your push method. Your Node first = new Node();
is hiding the field first
in your stack.
So, change:
Node first = new Node();
to
// This is your object field
first = new Node();
And the test will pass. Remember that you need to implement size()
since your test method uses it.
public int size(){
return N;
}