Question
I have the following method remove which is meant to remove the element at the specified index, but it does not work correctly. Using the
I have the following method "remove" which is meant to remove the element at the specified index, but it does not work correctly. Using the code :
List list = new LinkedList<>(); list.add(3); // [3] list.add(5); // [3, 5] list.add(7); // [3, 5, 7] System.out.println(list.remove(1));
The remove method should remove and return the element and index 1, so it should return 5, but my method returns 3. I need help fixing this. Thank you.
The following is the code that needs fixing.
// Removes and returns the element at the specified index,
// or throws an IndexOutOfBoundsException if the index is out of range.
public E remove(int index) {
if(index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bound...");
Node temp = first;
if(index == 0) {
--size;
first = first.next;
return temp.data;
}
// Find previous node of the node to be deleted
for (int i=0; i temp = temp.next; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node temp.next = next; // Unlink the deleted node from list --size; Node while(t.next != null) { t = t.next; } last = t; return temp.data; } // Adds element e to the top of the stack.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started