Basically I’m trying to remove consecutive duplicate numbers in a Linked List using recursion. My code is working fine for smaller size of Linked Lists but getting stackoverflow error for bigger size Linked lists. I am not able to figure out what’s the issue. Can anybody help.
/*
Following is the Node class already written for the Linked List
class Node<T> {
T data;
Node<T> next;
public Node(T data) {
this.data = data;
}
}
*/
public class Solution {
public static Node<Integer> removeDuplicates(Node<Integer> head) {
//recursive approach
if(head==null || head.next==null){
return head;
}
Node<Integer> smallAns = removeDuplicates(head.next);
if(smallAns.data.equals(head.data)){
return smallAns;
}else{
head.next = smallAns;
return head;
}
}
}
Sample Input 1 :
1 2 3 3 3 3 4 4 4 5 5 7 -1
Sample Output 1 :
1 2 3 4 5 7
New contributor
Aabid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.