I am trying to remove an item from the LinkedList in java. This List is implemented by me and I am not using any java API. The major trouble I am facing is with RECURSION as I am always lost in recursion coding.
class List{
int N;
List next;
List current;
List(int N){
this.N =N;
this.next = null;
}
@Override
public String toString() {
String o = "";
List curr = this;
while(curr != null){
o += curr.N+"-->";
curr = curr.next;
}
return o+"TAIL";
}
}
Method implemented:
private static List Remove(List L,int N){
if(L == null || L.next == null)
return L;
List current = L;
List previous = null;
while(current != null){
if(current.N == N){
current = current.next;
if(previous == null)previous = current;
else{
previous.next = current;
}
break;
}else{
previous = current;
current = current.next;
}
}
return previous;
}
Input –
List list1 = new List(1);
list1.next = new List(2);
list1.next.next = new List(3);
list1.next.next.next = new List(4);
list1.next.next.next.next = new List(5);
list1.next.next.next.next.next = new List(6);
list1.next.next.next.next.next.next = new List(7);
System.out.println("Before Removal "+list1.toString());
System.out.println("After Removal "+Remove(list1,3));
Output I am getting is –
- Before Removal 1–>2–>3–>4–>5–>6–>7–>TAIL
- After Removal 2–>4–>5–>6–>7–>TAIL
Here I am losing the value 1 as I am setting the current = current.next or reference is being set to next value. So definitely I am having some problem with the presentation of data stored in different references.
The mistake is here:
You should return the original head of the list if it was not removed. To show it graphically:
At this point by returning
previous, you lose the former head elementL.For the case when the head element is to be removed, you should add a separate check before the loop.
Btw your
Removemethod is not recursive – it is never calling itself.