Created
October 20, 2017 11:51
-
-
Save MohamedTaha98/d4591520c639744098706fe5ad51bcb4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
using namespace std; | |
/* Structure containing the number, the character, | |
and a pointer to the next node */ | |
struct node | |
{ | |
int n; char c; | |
node* next; | |
}; | |
// Class containing head, tail and functions | |
class linked_list | |
{ | |
private: | |
// Pointers to the beginning and end of the linked list. | |
node* head; | |
node* tail; | |
public: | |
// Initializing head and tail pointers to null to avoid segfault. | |
linked_list() | |
{ | |
head = NULL; | |
tail = NULL; | |
} | |
// Adding a node to the end of the linked list | |
void add(int n, char c) | |
{ | |
node* tmp = new node; | |
tmp->n = n; | |
tmp->c = c; | |
tmp->next = NULL; | |
// Check if there is a linked list, if not: Create one | |
if (head == NULL) | |
{ | |
head = tmp; | |
tail = tmp; | |
} | |
// Add a node to the tail of the linked list | |
else | |
{ | |
tail->next = tmp; | |
tail = tail->next; | |
} | |
} | |
// Show current contents of the linked list | |
void display() | |
{ | |
node* trav = head; | |
while (trav != NULL) | |
{ | |
cout << "C: " << trav->c << ", N: " << trav->n << endl; | |
trav = trav->next; | |
} | |
} | |
// Destroy the linked list to avoid memory leaks | |
void destroy(node* head) | |
{ | |
if (head == NULL) | |
return; | |
destroy(head->next); | |
delete head; | |
} | |
}; | |
int main() | |
{ | |
linked_list a; | |
cout << "Adding letters from A to Z, Numbers from 0 to 25: " << endl; | |
char c = 'A'; | |
for (int i = 0; i < 26; i++) | |
{ | |
a.add(i, c); | |
c++; | |
} | |
cout << "Now the list is: " << endl; | |
a.display(); | |
cout << "Destroying..." << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment