Created
March 31, 2021 02:50
-
-
Save lablnet/6fe67ae05058dd12a24ceb44354789cc to your computer and use it in GitHub Desktop.
C++ Dynamic list without quote unquote Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
//#include "List/List.h" | |
template <typename T> | |
class List { | |
private: | |
T *data; | |
T *tmp; | |
int storage = 1; | |
int used = 0; | |
void add(T item) { | |
this->data[this->used] = item; | |
this->used++; | |
} | |
public: | |
//List() = default; | |
List() { | |
this->data = (T*)malloc(this->storage * sizeof(T)); | |
} | |
void append(T item) { | |
if (this->used == this->storage) { | |
this->storage++; | |
this->tmp = (T*)realloc(this->data, this->storage * sizeof(T)); | |
this->data = this->tmp; | |
add(item); | |
} else { | |
add(item); | |
} | |
} | |
int size() { | |
return this->used; | |
} | |
int capacity() { | |
return this->storage; | |
} | |
bool empty() { | |
return this->used == 0; | |
} | |
~List() { | |
free(this->data); | |
free(this->tmp); | |
this->storage = 0; | |
this->used = 0; | |
} | |
void display() { | |
for (int i = 0; i < used; i++) { | |
std::cout << "item: " << this->data[i] << std::endl; | |
} | |
} | |
}; | |
int main() { | |
List<int> list;// = new List<int>(); | |
list.append(1); | |
list.append(2); | |
list.append(3); | |
list.append(4); | |
list.append(5); | |
list.display(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment