-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoNumbers_LinkedList.java
More file actions
91 lines (70 loc) · 2.21 KB
/
Copy pathTwoNumbers_LinkedList.java
File metadata and controls
91 lines (70 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//Given two numbers represented by two lists, write a function that returns sum list.
//The sum list is list representation of addition of two input numbers.
class TwoNumbers_LinkedList {
static Node head1, head2;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
Node addTwoLists(Node first, Node second) {
Node res = null;
Node prev = null;
Node temp = null;
int carry = 0, sum;
while (first != null || second != null) //while both lists exist
{
sum = carry + (first != null ? first.data : 0)
+ (second != null ? second.data : 0);
carry = (sum >= 10) ? 1 : 0;
sum = sum % 10;
temp = new Node(sum);
if (res == null) {
res = temp;
} else
{
prev.next = temp;
}
prev = temp;
if (first != null) {
first = first.next;
}
if (second != null) {
second = second.next;
}
}
if (carry > 0) {
temp.next = new Node(carry);
}
return res;
}
void printList(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println("");
}
public static void main(String[] args) {
TwoNumbers_LinkedList list = new TwoNumbers_LinkedList();
// creating first list
list.head1 = new Node(8);
list.head1.next = new Node(2);
list.head1.next.next = new Node(9);
list.head1.next.next.next = new Node(5);
list.head1.next.next.next.next = new Node(7);
System.out.print("First List is ");
list.printList(head1);
// creating second list
list.head2 = new Node(9);
list.head2.next = new Node(4);
System.out.print("Second List is ");
list.printList(head2);
Node rs = list.addTwoLists(head1, head2);
System.out.print("Resultant List is ");
list.printList(rs);
}
}