Please check my code its not passing 1 case I’ve tried atleast 4 solutions to this problem but only two cases are passing please help
import java.util.*;
class LinkedList {
private class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
private Node tail;
private int size;
public LinkedList() {
this.head = null;
this.tail = null;
this.size = 0;
}
public LinkedList(Node head, Node tail, int size) {
this.head = head;
this.tail = tail;
this.size = size;
}
// O(1)
public int size() {
return this.size;
}
// O(1)
public boolean isEmpty() {
return this.size() == 0;
}
// O(1)
// O(1)
public void addFirst(int item) {
Node newNode = new Node(item);
if(this.size==0) {
this.head=newNode;
this.tail=newNode;
size++;
}else {
newNode.next=head;
this.head=newNode;
size++;
}
}
//O(1)
public void addLast(int item) {
Node newNode = new Node(item);
if(this.size==0) {
this.head=newNode;
this.tail=newNode;
size++;
}else {
this.tail.next=newNode;
this.tail=newNode;
size++;
}
}
// O(n)
public void display() {
Node node = this.head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
//System.out.println("END");
}
public void sumLL(LinkedList list2, int n) throws Exception {
LinkedList ans=new LinkedList();
int carry=sumAns(this.head, list2.head,ans);
if(carry>0)
ans.addFirst(carry);
ans.display();
// sumDiff(head,list2.head,ans);
}
private int sumAns(Node head1, Node head2,LinkedList ans ) throws Exception {
if(head1==null && head2!=null){
ans.head=head2;
return 0;
}
if(head2==null && head1!=null){
ans.head=head1;
return 0;
}
if(head1==null && head2==null) {
return 0;
}
int carry=sumAns(head1.next,head2.next,ans);
int sum=head1.data + head2.data +carry;
carry=sum/10;
sum=sum%10;
ans.addFirst(sum);
return carry;
}
// int carry=0;
// public void sumLL(LinkedList list2, int n) {
// LinkedList ans=new LinkedList();
// sumAns(this.head, list2.head,ans);
// if(carry>0)
// ans.addFirst(carry);
// ans.display();
// }
// private void sumAns(Node head1, Node head2,LinkedList ans ) {
// if(head1==null){
// ans.head=head2;
// return;
// }
// if(head2==null){
// ans.head=head1;
// return;
// }
// // if(head1==null && head2==null) {
// // ans.head=null;
// // return;
// // }
// sumAns(head1.next,head2.next,ans);
// int sum=head1.data + head2.data +carry;
// carry=sum/10;
// sum=sum%10;
// ans.addFirst(sum);
// }
}
public class Main{
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
LinkedList list1 = new LinkedList();
LinkedList list2 = new LinkedList();
for(int i=0;i<n;i++) {
list1.addLast(sc.nextInt());
}
for(int i=0;i<m;i++) {
list2.addLast(sc.nextInt());
}
list1.sumLL(list2,n);
}
}
And Below that there’s a commented code which is also passing just 2 cases