How to Delete a String From a Doubly Linked List in Java?
The Java programming language comes with a series of included data structures such as linked lists or dictionaries. However, you may at some point want to create your own implementations of data structures to suit your own specific purposes. This also means implementing your own basic functions for the data structure, including insertion and deletion functions. In the case of a doubly linked list containing string values, this is a matter of ensuring that you find the node containing the string and linking the items before and after the deleted item to maintain the structure of the list.
Things You'll Need
- Java Development Kit (JDK)
- Text Editor or Integrated Development Environment (IDE)
Instructions
-
-
1
Locate the node of the linked list you are removing. In this example, the nodes of the doubly linked list are represented by the data item "ListItem," which contains a string (stored as "value") and two references to other ListItems: one "previous" to it and one "after" it in the list. The "findItem" function traverses the list until finding the node that contains the string value, returning a reference to that node:
public ListItem findItem(String word){
ListItem current = head; //head of the list
while (current.value != word){
current = current.next;
}return current;
} -
2
Create the skeleton of a function to remove the node. This function will call "findItem" to locate the node:
public void deleteItem(String word){
ListItem removing = findItem(word);
}
-
-
3
Modify the "deleteItem" function to link the previous node to the following node. To ensure that the doubly linked list remains unbroken, the previous node must be linked to the rest of the list following the node:
public void deleteItem(String word){
ListItem removing = findItem(word);
removing.previous.after = removing.after; //the previous node now links to the following node
} -
4
Modify the "deleteItem" function to link the following node to the previous node. To complete the link and maintain the list as a doubly linked list, the deleted node's following node now needs to link back to the deleted node's previous node:
public void deleteItem(String word){
ListItem removing = findItem(word);
removing.previous.after = removing.after;
removing.after.previous = removing.previous; //following node now links to the previous node
} -
5
Delete the node:
public void deleteItem(String word){
ListItem removing = findItem(word);
removing.previous.after = removing.after;
removing.after.previous = removing.previous;removing = null;
}
-
1