Skip to content

Instantly share code, notes, and snippets.

@yung-turabian
Last active March 27, 2024 17:35
Show Gist options
  • Save yung-turabian/f78ad5776e161ba21d89a42bb8d43ddc to your computer and use it in GitHub Desktop.
Save yung-turabian/f78ad5776e161ba21d89a42bb8d43ddc to your computer and use it in GitHub Desktop.
LinkedList in C++
#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