-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddLinked1.java
More file actions
112 lines (106 loc) · 1.24 KB
/
Copy pathAddLinked1.java
File metadata and controls
112 lines (106 loc) · 1.24 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
109
110
111
112
class AddLinked1
{
Node head;
class Node
{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
}
void append(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");
}
AddLinked1 AddLinked(Node head1,Node head2)
{
Node temp1=head1;
Node temp2=head2;
int x=0;
int y=0;
int carry=0;
int sum=0;
AddLinked1 l1=new AddLinked1();
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;
l1.append(sum%10);
if(temp1!=null)
{
temp1=temp1.next;
}
if(temp2!=null)
{
temp2=temp2.next;
}
}
if(carry!=0)
{
l1.append(carry);
}
return l1;
}
public static void main(String args[])
{
AddLinked1 l1=new AddLinked1();
l1.append(9);
l1.append(9);
l1.append(9);
l1.append(9);
l1.append(9);
l1.append(9);
l1.append(9);
l1.print();
AddLinked1 l2=new AddLinked1();
l2.append(9);
l2.append(9);
l2.append(9);
l2.append(9);
l2.print();
AddLinked1 l3=new AddLinked1();
System.out.println("Addtion of two linkedList");
l3=l3.AddLinked(l1.head,l2.head);
l3.print();
}
}