-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlistmatrix.cpp
More file actions
60 lines (43 loc) · 1.26 KB
/
Copy pathlinkedlistmatrix.cpp
File metadata and controls
60 lines (43 loc) · 1.26 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
#include <iostream>
#include <stdexcept>
#include "linkedlistmatrix.h"
Matrix::Matrix() : data(nullptr), right(nullptr), down(nullptr) {}
LinkedList2D::LinkedList2D() : head(nullptr) {}
void LinkedList2D::add(int row, int col, Node *value) {
if (row < 0 || col < 0) return;
if (!head) {
head = new Matrix();
}
Matrix* row_ptr = head;
// Navigate to the correct row
for (int i = 0; i < row; ++i) {
if (!row_ptr->down) {
row_ptr->down = new Matrix();
}
row_ptr = row_ptr->down;
}
// Navigate to the correct column
for (int j = 0; j < col; ++j) {
if (!row_ptr->right) {
row_ptr->right = new Matrix();
}
row_ptr = row_ptr->right;
}
// Set the value at the node
row_ptr->data = value;
}
Node* LinkedList2D::get(int row, int col) {
if (row < 0 || col < 0) return nullptr;
Matrix* row_ptr = head;
// Navigate to the correct row
for (int i = 0; i < row; ++i) {
if (!row_ptr) return nullptr;
row_ptr = row_ptr->down;
}
// Navigate to the correct column
for (int j = 0; j < col; ++j) {
if (!row_ptr) return nullptr;
row_ptr = row_ptr->right;
}
return row_ptr ? row_ptr->data : nullptr;
}