Java Removing Element from List

  • Context: Comp Sci 
  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Element Java List
Click For Summary
SUMMARY

The discussion centers on a Java implementation for removing an element from a doubly linked list, specifically the node right before the tail. The provided code snippet encounters an issue during execution, particularly at the line where the previous node's next pointer is updated. Users identify that the creation of an unnecessary empty Node object may lead to a NoSuchElementException when attempting to access its _data field. The code functions correctly for removing the front element, indicating a potential logical error in handling the back removal process.

PREREQUISITES
  • Understanding of Java programming language
  • Knowledge of data structures, specifically doubly linked lists
  • Familiarity with exception handling in Java
  • Experience with object-oriented programming concepts
NEXT STEPS
  • Review Java exception handling techniques to manage NoSuchElementException
  • Study the implementation of doubly linked lists in Java
  • Learn about optimizing node management in linked list operations
  • Explore debugging techniques for Java code execution issues
USEFUL FOR

Java developers, computer science students, and software engineers working with data structures and linked list implementations.

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 ·
Replies
9
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
4
Views
3K
  • · Replies 11 ·
Replies
11
Views
12K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 2 ·
Replies
2
Views
6K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K