Reputation: 8395
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 -
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.
Upvotes: 0
Views: 3892
Reputation: 6376
It's simply because you are not returning the head - but instead the previous pointer to the node you just 'removed':
static List Remove(final List L, final int N) {
// Base case for null head pointer
final List head = L;
if (head == null)
return head;
// Base case for removing the head
if (head.N == N)
return head.next;
List current = head.next;
List previous = head;
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 head;
}
Also - to clarify - this is not a recursive solution.
Upvotes: 1
Reputation: 116266
The mistake is here:
return previous;
You should return the original head of the list if it was not removed. To show it graphically:
N == 3
List Before Removal: 1-->2-->3-->4-->5-->6-->7-->TAIL
At start of iteration 1:
L ^
previous (null)
current ^
No match -> iteration 2:
L ^
previous ^
current ^
No match -> iteration 3:
L ^
previous ^
current ^
Match -> remove current:
List After Removal: 1-->2-->4-->5-->6-->7-->TAIL
L ^
previous ^
current ^
At this point by returning previous
, you lose the former head element L
.
For the case when the head element is to be removed, you should add a separate check before the loop.
Btw your Remove
method is not recursive - it is never calling itself.
Upvotes: 2