I think you make a mistake.
When you remove the first element of your list, you should change the head
to the second node. So you should write:
if (i == 0) {
head = crt.next;
return crt.content;
}
Question
Ok, so I'm trying to make a method that takes as parameter an object, and removes the element before that one if it is found in the single linked list. My problem is when I am searching for the 2nd element. It follows the if (i == 0)
but doesn't work and I'm not sure why. Can you please look at my code and tell me why it's not working?
main:
package SingleLinkedLists;
public class TestList {
public static void main(String[] args) {
SingleLinkedList testList = new SingleLinkedList();
testList.insertLast(1);
testList.insertLast(2);
testList.insertLast(3);
testList.insertLast(4);
testList.insertLast(5);
testList.print();
System.out.println("This is what I'm taking out: " + testList.removeBefore(2));
testList.print();
}
}
method:
public Object removeBefore(Object o) {
int i = 0;
if (o == null)
throw new NoSuchElementException("No such element");
Node crt = head;
Node prev = crt;
// trying to find the element right before the parameter
while(crt.next != null && !o.equals(crt.next.content)) {
prev = crt;
crt = crt.next;
i++;
}
if (i == 0) {
prev = crt.next;
crt.next = null;
return crt.content;
}
if (crt.next == null)
throw new NoSuchElementException("No such element");
// remove crt node from list
prev.next = crt.next;
crt.next = null;
// return the removed content
return crt.content;
}
output:
> run SingleLinkedLists.TestList
1
2
3
4
5
This is what I'm taking out: 1
1
>
output when using third element as passed parameter (3):
> run SingleLinkedLists.TestList
1
2
3
4
5
This is what I'm taking out: 2
1
3
4
5
>
Thanks
Solution
I think you make a mistake.
When you remove the first element of your list, you should change the head
to the second node. So you should write:
if (i == 0) {
head = crt.next;
return crt.content;
}