Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- }
Add Comment
Please, Sign In to add comment