Created
February 17, 2024 05:53
-
-
Save alekxeyuk/c42e4b00c51b0e17260a19067ff6c6c5 to your computer and use it in GitHub Desktop.
List struct
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> | |
struct Node { | |
Node* next; | |
int value; | |
}; | |
struct List | |
{ | |
Node* first; | |
size_t size; | |
List() { | |
first = nullptr; | |
size = 0; | |
} | |
List(int v) { | |
first = new Node{ nullptr, v }; | |
size = 1; | |
} | |
List(const List& other) { | |
Node* p = other.first; | |
size = 0; | |
first = nullptr; | |
Node* e = first; | |
while (p != nullptr) { | |
e = pushBack(e, p->value); | |
p = p->next; | |
} | |
} | |
~List() { | |
if (first != nullptr) { | |
Node* p = first; | |
Node* n = first->next; | |
while (p != nullptr) { | |
delete p; | |
p = n; | |
if (p != nullptr) | |
n = p->next; | |
} | |
} | |
} | |
void pushBack(int value) { | |
pushBack(first, value); | |
} | |
void pushFront(int value) { | |
first = pushFront(first, value); | |
} | |
void print() const { | |
Node* p = first; | |
while (p != nullptr) { | |
std::cout << p->value << ' '; | |
p = p->next; | |
} | |
} | |
private: | |
Node* constructNode(int value) { | |
Node* newNode = new Node{ nullptr, value }; | |
return newNode; | |
} | |
Node* pushBack(Node* first, int value) { | |
Node* newNode = constructNode(value); | |
if (first == nullptr) { | |
first = newNode; | |
this->first = first; | |
} | |
else { | |
Node* last = first; | |
while (last->next != nullptr) { | |
last = last->next; | |
} | |
last->next = newNode; | |
} | |
size++; | |
return newNode; | |
} | |
Node* pushFront(Node* first, int value) { | |
Node* newNode = constructNode(value); | |
newNode->next = first; | |
size++; | |
return newNode; | |
} | |
}; | |
struct MyStruct | |
{ | |
int a; | |
double b; | |
int c; | |
}; | |
int main() { | |
List l = List(); | |
l.pushFront(90); | |
l.pushBack(10); | |
l.pushBack(20); | |
l.pushBack(30); | |
l.pushBack(40); | |
l.pushFront(80); | |
l.print(); | |
std::cout << '\n' << l.size; | |
std::cout << "\n------\n"; | |
List b = l; | |
b.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment