'How to delete a node from a circular linked list in Java?
Given a Circular linked list write a method in Java to delete a node.
Solution 1:[1]
There are really four cases to consider for this.
Case 1:
Is the list empty? If so return null or return
Case 2:
There is only one element in the list. Set the pointer to null and the list to null.
Case 3:
Delete something in the front of the list. In this case we have a few steps.
Steps:
- Make a temporary pointer to the list.
- Move to the end of the list.
- Set the temp pointer to the front of the list.
- Move the front of the list forward.
- Set temp's pointer to null.
- Set the end of the list to point to the new front of the list.
Case 4:
Delete something in this format 1->2->3-> where we are deleting the middle item. Note. This works for deleting the last item as well since it loops back around to 1.
Steps
- Make a temp pointer to the list.
- Move the temp pointer forward until we find the data to delete.
- Make a delete node (Example Node delete) and set it to temp's pointer.
- Set temp to skip over the node we are deleting.
Set the delete node's pointer to null.
public void delete(int data) { // Null list case if(list == null) return; // Delete the only element case if(list.data == data && list.next.data == list.data) { list.next = null; list = null; return; } // Delete the front of the list case if(list.data == data) { // Move to the end of the list Node end = list; while(end.next.data != list.data) { end = end.next; } Node temp = list; list = list.next; temp.next = null; end.next = list; return; } // Delete something in the middle Node temp = list; while(temp.next.data != data && temp.next.data != list.data) { temp = temp.next; } // We circled the list and did not find the element to delete if(temp.next.data == list.data) return; Node del = temp.next; temp.next = temp.next.next; del.next = null; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris Chaffin |