Last active
March 27, 2024 17:35
-
-
Save yung-turabian/f78ad5776e161ba21d89a42bb8d43ddc to your computer and use it in GitHub Desktop.
LinkedList in C++
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 <cstddef> | |
#include <iostream> | |
class LinkedList { | |
struct Node { | |
int data; | |
Node *next; | |
}; | |
public: | |
Node *head; | |
LinkedList() { | |
head = NULL; | |
} | |
~LinkedList() { | |
Node *next = head; | |
while(next) { | |
Node *deleteMe = next; | |
next = next->next; | |
delete deleteMe; | |
} | |
} | |
void append(int val) { | |
if (head == NULL) { | |
head = new Node(); | |
head->data = val; | |
head->next = NULL; | |
return; | |
} | |
Node *current = head; | |
while(current->next != NULL) { | |
current = current->next; | |
} | |
current->next = new Node(); | |
current->next->data = val; | |
current->next->next = NULL; | |
} | |
void print() { | |
Node *current = head; | |
do { | |
std::cout << current->data << std::endl; | |
current = current->next; | |
} | |
while(current != NULL); | |
} | |
}; | |
int main() { | |
LinkedList list; | |
list.append(5); | |
list.append(14); | |
list.append(69); | |
list.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment