Brittney P.

asked • 09/25/21

Removing an element from a circular linked list

Here I have my code that deletes a given integer value from a circular linked list:

public void remove(int item){
Node temp = tail.next; //Refers to the first index
Node prev_node= null;
if (temp.value == item) { // If item is first element
tail.next = temp.next;
} else {
while (temp != tail && temp.value != item) {
prev_node = temp;
temp = temp.next;
}

if (temp == tail) {
if (tail.value != item) {
return;
} else {
prev_node.next = tail.next;
tail = prev_node.next;
}
} else {
prev_node.next = temp.next;
}
}
}

My code works until the temp node is equal to the tail. For example, let's say I have a circular linked list and the data (not memory allocation) within a list would be [1,2,3,4]. If I want to delete 4 out of the circular linked list, it will delete it but the order is [2,3,1]. The first element then appears at the end of the list. I'm not sure exactly what I have done wrong. I know the error is in the second if statement.

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.