-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_numbers_represented_by_ll.cpp
More file actions
89 lines (68 loc) · 1.54 KB
/
Copy pathadd_numbers_represented_by_ll.cpp
File metadata and controls
89 lines (68 loc) · 1.54 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
//add numbers represented by LL
//https://ide.geeksforgeeks.org/ZoHr7P69xu
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
};
void printLL(struct Node* head){
if(head == NULL) return;
while(head!=NULL){
cout<<head->data<<" ";
head = head->next;
}
cout<<"\n";
}
int countLL(struct Node *head){
if(head == NULL) return 0;
int cnt = 1;
while(head){
cnt++;
head = head->next;
}
return cnt;
}
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
void addLL(Node *first, Node *second){
int sum = 0, carry = 0;
Node *temp;
Node *prev = NULL;
Node *res = NULL;
while(first != NULL || second != NULL){
sum = carry + (first? first->data : 0) + (second? second->data : 0);
carry = (sum) > 10 ? 1:0;
sum = sum%10;
temp = newNode(sum);
if(res == NULL){
res = temp;
}
else{
prev->next = temp;
}
prev = temp;
if(first)
first = first->next;
if(second)
second = second->next;
}
if(carry > 0) temp->next = newNode(carry);
printLL(res);
}
int main()
{
Node* head1 = newNode(9);
head1->next = newNode(2);
head1->next->next = newNode(3);
Node* head2 = newNode(1);
head2->next = newNode(2);
head2->next->next = newNode(3);
addLL(head1, head2);
return 0;
}