summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorsteven@devbox <steven@devbox.local>2025-05-10 11:11:59 +0000
committersteven@devbox <steven@devbox.local>2025-05-10 11:11:59 +0000
commitaa439b21d8f2809202b18b624d3b4759ba560e35 (patch)
tree48758ce064ca6cb992c360ead5db2832013b6a8b
parentca080c19f1f3f8e3c23a207d936d03fd5f247d12 (diff)
downloadcpp-master.tar.gz
cpp-master.tar.bz2
cpp-master.zip
insert_after an indexHEADmaster
-rw-r--r--src/main.cpp64
1 files changed, 39 insertions, 25 deletions
diff --git a/src/main.cpp b/src/main.cpp
index c5720bd..5c02248 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -2,8 +2,11 @@
static int NUMITEMS = 30;
static int NULPTR = -1;
static std::string DATA[] = {
- "Joe Australia", "Mark Carney", "Geert Wilders", "Mark Rutte",
- "Donald J. Trump", "Xi Jinping", "Adolf Hitler"};
+ "Joe Australia",
+ "Mark Carney",
+ "Donald J. Trump",
+ "Geert Wilders",
+};
class Node {
public:
std::string value;
@@ -14,6 +17,18 @@ public:
int root;
int free;
Node *src;
+ LinkedList() {
+ std::printf("Called constructor\n");
+ root = NULPTR;
+ free = 0;
+ src = new Node[NUMITEMS];
+ for (int i = 0; i < NUMITEMS; i++) {
+ Node n;
+ n.next = i + 1;
+ src[i] = n;
+ }
+ src[NUMITEMS - 1].next = NULPTR; // set last ptr
+ }
void show() {
int i = root;
while (i != NULPTR) {
@@ -21,7 +36,7 @@ public:
<< std::endl;
i = src[i].next;
}
- };
+ }
void insert(std::string element) {
src[free].value = element;
int next = src[free].next;
@@ -29,6 +44,21 @@ public:
root = free;
free = next;
}
+ void insert_after(std::string element, int index) {
+ int ptr = root;
+ int i = 0;
+ while (ptr != NULPTR) {
+ if (i == index) {
+ src[free].value = element;
+ int next = src[ptr].next;
+ src[ptr].next = free;
+ src[free].next = next;
+ free = src[free].next;
+ }
+ i++;
+ ptr = src[ptr].next;
+ }
+ }
bool find(std::string element) {
int i = root;
while (i != NULPTR) {
@@ -39,33 +69,17 @@ public:
}
return false;
}
+ ~LinkedList() { delete[] src; }
};
int main() {
- std::cout << "hello cpp" << std::endl;
- int x = 0;
LinkedList l;
- l.root = NULPTR;
- l.free = 0;
- Node nodes[NUMITEMS];
- for (int i = 0; i < NUMITEMS; i++) {
- Node n;
- n.value = "X";
- n.next = i + 1;
- nodes[i] = n;
- }
- nodes[NUMITEMS - 1].next = NULPTR; // set last ptr
- l.src = nodes;
for (const std::string &elem : DATA) {
+ std::cout << "element: " << elem << std::endl;
+ // std::cout << "root: " << l.root << "\tfree: " << l.free << std::endl;
l.insert(elem);
- }
- l.show();
- bool f1 = l.find("Xi");
- bool f2 = l.find("Steven");
- if (f1) {
- std::printf("Found Xi\n");
- }
- if (f2) {
- std::printf("Found Steven\n");
}
+ l.show();
+ l.insert_after("Putin", 0);
+ l.show();
return 0;
}