A
A
Andrey Kulagin2020-06-24 21:59:00
Java
Andrey Kulagin, 2020-06-24 21:59:00

How to remove the last element in a stack, based on a singly linked list?

The method must return a value and remove it from the collection

public T deleteLast() throws NoSuchElementException {
if (head == null) {
throw new NoSuchElementException("The list is empty");
}

Node ref = head;
for (int i = 0; i < size; i++) {
ref = ref.next;
}
size--;
T temp = ref value;
refnext = null;
return temp;
}

There is a test:

@Test
public void whenPushPollThenPushPoll() {
SimpleStack stack = new SimpleStack<>();
stack.push(1);
stack.pop();
stack.push(2);
assertThat(stack.pop(), is(2));
}

The test does not work because the deleteLast() method is not implemented correctly, probably not correctly deleting the last node (I do this with ref.next = null;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Pokrovsky, 2020-06-24
@Makaroshka007

Maybe so?
for (int i = 0; i < size - 1; i++) {...}

D
Denis Zagaevsky, 2020-06-25
@zagayevskiy

There is no operation to remove the last element on the stack. In a singly linked list, this is generally the most expensive operation, why is it?
Further, in the test you do not use this function.
In any case, the function is implemented fundamentally incorrectly.
You need to take into account the edge case size == 1 and set head to zero. You need to iterate (size - 2) times to get to the penultimate element, and set its next to zero. You need to take value from the element following the one for which next is set to zero. That is at the very next'a.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question