[AlgoExpert] Sum of Linked Lists

Sum of Linked Lists

  • Time : O(n + m)
  • Space : O(n + m)
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
using namespace std;

// This is an input struct. Do not edit.
class LinkedList {
public:
int value;
LinkedList *next = nullptr;

LinkedList(int value) { this->value = value; }
};

LinkedList *sumOfLinkedLists(LinkedList *linkedListOne,
LinkedList *linkedListTwo) {
int append = 0;
LinkedList* dummy = new LinkedList(-1);
LinkedList* tail = dummy;
while(linkedListOne and linkedListTwo) {
int sum = append + linkedListOne->value + linkedListTwo->value;
linkedListOne = linkedListOne->next;
linkedListTwo = linkedListTwo->next;
append = sum / 10;
sum = sum % 10;
LinkedList* newTail = new LinkedList(sum);
tail->next = newTail;
tail = newTail;
}
while(linkedListOne) {
int sum = append + linkedListOne->value;
linkedListOne = linkedListOne->next;
append = sum / 10;
sum = sum % 10;
LinkedList* newTail = new LinkedList(sum);
tail->next = newTail;
tail = newTail;
}
while(linkedListTwo) {
int sum = append + linkedListTwo->value;
linkedListTwo = linkedListTwo->next;
append = sum / 10;
sum = sum % 10;
LinkedList* newTail = new LinkedList(sum);
tail->next = newTail;
tail = newTail;
}
if(append) {
LinkedList* newTail = new LinkedList(append);
tail->next = newTail;
tail = newTail;
}
return dummy->next;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/14/PS/AlgoExpert/sum-of-linked-lists/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.