11package com .shekhargulati .leetcode .algorithms ;
22
33import java .util .ArrayList ;
4- import java .util .Arrays ;
54import java .util .List ;
65
76/**
@@ -23,15 +22,16 @@ public static void main(String[] args) {
2322 */
2423
2524 long start = System .currentTimeMillis ();
26- List < Integer > first = Arrays . asList (2 , 4 , 3 );
27- List < Integer > second = Arrays . asList (5 , 6 , 4 );
25+ ListNode first = new ListNode (2 , new ListNode ( 4 , new ListNode ( 3 , null )) );
26+ ListNode second = new ListNode (5 , new ListNode ( 6 , new ListNode ( 4 , null )) );
2827
2928 List <Integer > result = new ArrayList <>();
30-
3129 int rem = 0 ;
32- for (int i = 0 ; i < first .size (); i ++) {
33- int a = first .get (i );
34- int b = second .get (i );
30+ while (first != null && second != null ) {
31+ int a = first .val ;
32+ int b = second .val ;
33+ first = first .next ;
34+ second = second .next ;
3535 int sum = a + b ;
3636 if (a + b >= 10 ) {
3737 result .add (rem + sum % 10 );
@@ -41,20 +41,31 @@ public static void main(String[] args) {
4141 rem = 0 ;
4242 }
4343 }
44-
45- System .out .println (result );
4644 long end = System .currentTimeMillis ();
4745 System .out .println (String .format ("Total time taken %d millis" , (end - start )));
4846
4947 }
5048
51- private class ListNode {
49+ private static class ListNode {
5250 int val ;
5351 ListNode next ;
5452
53+ public ListNode (int val , ListNode next ) {
54+ this .val = val ;
55+ this .next = next ;
56+ }
57+
5558 public ListNode (int val ) {
5659 this .val = val ;
5760 }
61+
62+ @ Override
63+ public String toString () {
64+ return "ListNode{" +
65+ "val=" + val +
66+ ", next=" + next +
67+ '}' ;
68+ }
5869 }
5970
6071}
0 commit comments