Untitled
/* class Node{ int data; Node next; Node(int data){ this.data = data; this.next = null; } } */ class Solution{ public Node addTwoLinkedList(Node head1,Node head2){ //write your code here. int c = 0; ArrayList<Integer> arr = new ArrayList<>(); while(head1 != null && head2 != null){ // System.out.println(head1.data+" "+head2.data); int sum = head1.data+head2.data+c; if(sum>9){ c=sum/10; sum %= 10; } else c = 0; arr.add(sum); head1 = head1.next; head2 = head2.next; } while(head1 != null && c != 0){ int sum = head1.data+c; if(sum>9){ c=sum/10; sum %= 10; } else c = 0; arr.add(sum); head1 = head1.next; } while(head2 != null && c!= 0){ int sum = head2.data+c; if(sum>9){ c=sum/10; sum %= 10; } else c = 0; arr.add(sum); head2 = head2.next; } Node ans = null; Node curr = null; for(Integer i:arr){ Node n1 = new Node(i); if(ans == null){ ans = n1; curr = ans; } else{ curr.next = n1; } curr = n1; } while(c!=0){ Node n1 = new Node(c%10); c/=10; if(ans == null){ ans = n1; curr = ans; } else{ curr.next = n1; } curr = n1; } return ans; } }
Leave a Comment