Comp Sci Java Removing Element from List

AI Thread Summary
The discussion focuses on a Java code snippet intended to remove an element from the back of a list using dummy head and tail nodes. The user reports that the code compiles but does not execute as expected, particularly at the line where it attempts to adjust pointers for the nodes. A response indicates that the code appears correct for removing the last element, questioning what is meant by "no execution." Additionally, it points out that an unnecessary empty node is created, which could lead to returning empty data or causing an exception. The issue may stem from the handling of the Node class or the logic around the cursor manipulation.
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.
 

Similar threads

Replies
9
Views
4K
Replies
3
Views
2K
Replies
11
Views
12K
Replies
5
Views
3K
Replies
2
Views
4K
Replies
2
Views
6K
Replies
1
Views
1K
Replies
2
Views
1K
Back
Top