Skip to content

Commit 0dcbad3

Browse files
committed
Problem02 using ListNode
1 parent d7dd40c commit 0dcbad3

1 file changed

Lines changed: 21 additions & 10 deletions

File tree

  • java8/src/main/java/com/shekhargulati/leetcode/algorithms

java8/src/main/java/com/shekhargulati/leetcode/algorithms/Problem02.java

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.shekhargulati.leetcode.algorithms;
22

33
import java.util.ArrayList;
4-
import java.util.Arrays;
54
import 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

Comments
 (0)