Java Removing Element from List

  • Context: Comp Sci 
  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Element Java List
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
magnifik
Messages
350
Reaction score
0
i am trying to remove an element from the back of the list (i.e. the node right before the tail). i am using a dummy head and tail node. the code compiles correctly, but when i try to test it, there is no execution. below is the segment of code that i am referring to:


public Object removeBack() {
if (_size == 0) throw new NoSuchElementException();
Node node = new Node();
Node cursor = _tail._prev;
cursor._next._prev = cursor._prev;
cursor._prev._next = cursor._next; // this is the line of code giving me error
_size--;
return node._data;
}

i am not sure what is wrong with my code. it works properly when trying to removeFront, and the only change from that segment of the code is the cursor.
 
Physics news on Phys.org
Hi magnifik! :smile:

Your code appears to correctly remove the last element in the list, so what do you mean that there is no execution?

Btw, you do create an unnecessary empty "node", of which you try to return the _data field, which will probably be empty.
Depending on how defined your Node class, this could even result in an exception.