-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.cpp
More file actions
94 lines (79 loc) · 1.95 KB
/
2.cpp
File metadata and controls
94 lines (79 loc) · 1.95 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
#include <vector>
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
// Cria uma lista encadeada a partir de um vetor
ListNode *createList(const vector<int> &values)
{
ListNode *head = nullptr;
ListNode *tail = nullptr;
for (int val : values)
{
ListNode *newNode = new ListNode(val);
if (head == nullptr)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// Imprime uma lista encadeada
void imprimirLista(ListNode *head)
{
cout << "[";
while (head != nullptr)
{
cout << head->val;
if (head->next)
cout << ",";
head = head->next;
}
cout << "]" << endl;
}
int main()
{
// Listas de exemplo
vector<int> n1 = {9, 9, 9, 9, 9, 9, 9};
vector<int> n2 = {9, 9, 9, 9};
ListNode *l1 = createList(n1);
ListNode *l2 = createList(n2);
cout << "Lista 1: ";
imprimirLista(l1);
cout << "Lista 2: ";
imprimirLista(l2);
cout << endl;
// Nó auxiliar dummy para construir a lista de resultado
ListNode *dummy = new ListNode(0);
ListNode *current = dummy;
int parser = 0; // carry
// Loop de soma
while (l1 != nullptr || l2 != nullptr || parser != 0)
{
int x = (l1 != nullptr) ? l1->val : 0;
int y = (l2 != nullptr) ? l2->val : 0;
int sum = x + y + parser;
current->next = new ListNode(sum % 10);
parser = sum / 10;
current = current->next;
if (l1 != nullptr) l1 = l1->next;
if (l2 != nullptr) l2 = l2->next;
}
// Lista final de soma
ListNode *answer = dummy->next;
cout << "Resultado: ";
imprimirLista(answer);
return 0;
}