1+ package linkedList ;
2+ // Problem Title => Add two numbers represented by linked lists.
3+
4+ public class Problem_10 {
5+
6+ static Node head1 , head2 ;
7+
8+ static class Node {
9+ int data ;
10+ Node next ;
11+
12+ Node (int d ) {
13+ data = d ;
14+ next = null ;
15+ }
16+ }
17+
18+ Node addTwoLists (Node first , Node second ) {
19+ Node res = null , prev = null , temp = null ;
20+ int carry = 0 , sum ;
21+
22+ while (first != null || second != null ) {
23+ sum = carry + (first != null ? first .data : 0 ) + (first != null ? first .data : 0 );
24+ carry = (sum >= 0 ) ? 1 : 0 ;
25+ temp = new Node (sum );
26+
27+ if (res == null )
28+ res = temp ;
29+
30+ else
31+ prev .next = temp ;
32+
33+ prev = temp ;
34+
35+ // Move first and second pointers to next nodes
36+ if (first != null )
37+ first = first .next ;
38+
39+ if (second != null )
40+ second = second .next ;
41+ }
42+
43+ if (carry > 0 )
44+ temp .next = new Node (carry );
45+
46+ // return head of the resultant list
47+ return res ;
48+ }
49+
50+ /* Utility function to print a linked list */
51+
52+ void printList (Node head ) {
53+ while (head != null ) {
54+ System .out .print (head .data + " " );
55+ head = head .next ;
56+ }
57+ System .out .println ("" );
58+ }
59+
60+ public static void main (String [] args ) {
61+
62+ Problem_10 list = new Problem_10 ();
63+ Problem_10 .head1 = new Node (7 );
64+ Problem_10 .head1 .next = new Node (5 );
65+ Problem_10 .head1 .next .next = new Node (9 );
66+ Problem_10 .head1 .next .next .next = new Node (4 );
67+ Problem_10 .head1 .next .next .next .next = new Node (6 );
68+ System .out .print ("First List is " );
69+ list .printList (head1 );
70+
71+ // creating seconnd list
72+ Problem_10 .head2 = new Node (8 );
73+ Problem_10 .head2 .next = new Node (4 );
74+ System .out .print ("Second List is " );
75+ list .printList (head2 );
76+
77+ // add the two lists and see the result
78+ Node rs = list .addTwoLists (head1 , head2 );
79+ System .out .print ("Resultant List is " );
80+ list .printList (rs );
81+ }
82+ }
0 commit comments