-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddLink.java
More file actions
108 lines (98 loc) · 1.12 KB
/
Copy pathAddLink.java
File metadata and controls
108 lines (98 loc) · 1.12 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
class AddLink
{
Node head;
class Node
{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
}
void push(int data)
{
Node x=new Node(data);
if(head==null)
{
head=x;
return;
}
Node temp=head;
while(temp.next!=null)
{
temp=temp.next;
}
temp.next=x;
}
void print()
{
Node temp=head;
while(temp!=null)
{
System.out.print(temp.data+"->");
temp=temp.next;
}
System.out.println("null");
}
AddLink AddTwoLink(Node head1,Node head2)
{
Node temp1=head1;
Node temp2=head2;
int x=0;
int y=0;
int sum=0;
int carry=0;
AddLink l=new AddLink();
while(temp1!=null|| temp2!=null)
{
if(temp1!=null)
{
x=temp1.data;
}else{
x=0;
}
if(temp2!=null)
{
y=temp2.data;
}else
{
y=0;
}
sum=carry+x+y;
carry=sum/10;
l.push(sum%10);
if(temp1!=null)
temp1=temp1.next;
if(temp2!=null)
temp2=temp2.next;
}
if(carry!=0)
{
l.push(carry);
}
return l;
}
public static void main(String args[])
{
AddLink a=new AddLink();
a.push(9);
a.push(9);
a.push(9);
a.push(9);
a.push(9);
a.push(9);
a.push(9);
a.print();
AddLink a1=new AddLink();
a1.push(9);
a1.push(9);
a1.push(9);
a1.push(9);
a1.print();
AddLink a2=new AddLink();
a2=a2.AddTwoLink(a.head,a1.head);
a2.print();
}
}