summaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: 5c022481b7d00de49b0357c895409190fecb23d3 (plain)
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
#include <iostream>
static int NUMITEMS = 30;
static int NULPTR = -1;
static std::string DATA[] = {
    "Joe Australia",
    "Mark Carney",
    "Donald J. Trump",
    "Geert Wilders",
};
class Node {
public:
  std::string value;
  int next;
};
class LinkedList {
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) {
      std::cout << "[" << i << "] " << src[i].value << " -> " << src[i].next
                << std::endl;
      i = src[i].next;
    }
  }
  void insert(std::string element) {
    src[free].value = element;
    int next = src[free].next;
    src[free].next = root;
    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) {
      if (src[i].value == element) {
        return true;
      }
      i = src[i].next;
    }
    return false;
  }
  ~LinkedList() { delete[] src; }
};
int main() {
  LinkedList l;
  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();
  l.insert_after("Putin", 0);
  l.show();
  return 0;
}