Skip to content

Instantly share code, notes, and snippets.

@DreamVB
Last active June 4, 2021 20:44
Show Gist options
  • Save DreamVB/1fe0f44e5ca771a8c517dd73aa8c0af4 to your computer and use it in GitHub Desktop.
Save DreamVB/1fe0f44e5ca771a8c517dd73aa8c0af4 to your computer and use it in GitHub Desktop.
Linked List Demo
//Linked List Demo
#include <iostream>
using namespace std;
template <typename T>
class LList{
public:
struct Node{
T data;
Node *next;
};
Node *head;
Node *tail;
LList(){
head = NULL;
tail = NULL;
}
~LList(){
Node *n = head;
while (n != NULL){
n = n->next;
delete(head);
head = n;
}
}
const void add_node(T data){
Node *n = new Node();
n->data = data;
n->next = NULL;
if (head == NULL){
head = n;
tail = n;
n = NULL;
}
else{
tail->next = n;
tail = n;
}
}
const void InsertFirst(T data){
Node *n = new Node();
n->data = data;
n->next = head;
head = n;
}
const void InsertLast(T data){
add_node(data);
}
const void InsertAt(int index, T data){
size_t x = 0;
Node * cur = head;
Node *temp = new Node();
Node *pre = new Node();
if (head == NULL){
return;
}
while (x < index){
pre = cur;
cur = cur->next;
x++;
}
temp->data = data;
pre->next = temp;
temp->next = cur;
}
const void delete_first(void){
if (head != NULL){
Node *n = head;
head = head->next;
delete(n);
}
}
const void delete_last(void){
Node *cur;
Node *prev = new Node();
cur = head;
while (cur->next != NULL)
{
prev = cur;
cur = cur->next;
}
tail = prev;
prev->next = NULL;
delete(cur);
}
const void deleteByIndex(int index){
Node *cur = head;
size_t x = 0;
Node *prev = new Node();
while (x < index){
prev = cur;
cur = cur->next;
x++;
}
prev->next = cur->next;
}
Node* find(T data){
Node *n = head;
bool found = false;
if (head != NULL){
while (n != NULL){
if (n->data == data){
found = true;
break;
}
n = n->next;
}
}
return n;
}
const void destroy_nodes(void){
Node *n = head;
while (n != NULL){
n = n->next;
delete(head);
head = n;
}
}
const size_t size() const{
Node *n = head;
size_t x = 0;
while (n != NULL){
x++;
n = n->next;
}
return x;
}
const void display_nodes(void){
Node *n = head;
while (n != NULL){
std::cout << n->data << std::endl;
n = n->next;
}
}
};
int main(){
LList<int> nums;
LList<int>::Node *f;
nums.add_node(10);
nums.add_node(20);
nums.add_node(30);
nums.add_node(40);
nums.deleteByIndex(2);
nums.display_nodes();
f = nums.find(40);
if (f != NULL){
std::cout << f->data << " was found." << std::endl;
}
std::cout << std::endl;
nums.InsertFirst(60);
nums.InsertLast(255);
nums.display_nodes();
system("pause");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment