SHARE
TWEET

Untitled

a guest Oct 21st, 2017 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. /* Structure containing the number, the character,
  6. and a pointer to the next node */
  7. struct node
  8. {
  9.     int n; char c;
  10.     node* next;
  11. };
  12.  
  13. // Class containing head, tail and functions
  14. class linked_list
  15. {
  16. private:
  17.     // Pointers to the beginning and end of the linked list.
  18.     node* head;
  19.     node* tail;
  20.  
  21. public:
  22.     // Initializing head and tail pointers to null to avoid segfault.
  23.     linked_list()
  24.     {
  25.         head = NULL;
  26.         tail = NULL;
  27.     }
  28.     // Adding a node to the end of the linked list
  29.     void add(int n, char c)
  30.     {
  31.         node* tmp = new node;
  32.         tmp->n = n;
  33.         tmp->c = c;
  34.         tmp->next = NULL;
  35.         // Check if there is a linked list, if not: Create one
  36.         if (head == NULL)
  37.         {
  38.             head = tmp;
  39.             tail = tmp;
  40.         }
  41.         // Add a node to the tail of the linked list
  42.         else
  43.         {
  44.             tail->next = tmp;
  45.             tail = tail->next;
  46.         }
  47.     }
  48.     // Show current contents of the linked list
  49.     void display()
  50.     {
  51.         node* trav = head;
  52.         while (trav != NULL)
  53.         {
  54.             cout << "C: " << trav->c << ", N: " << trav->n << endl;
  55.             trav = trav->next;
  56.         }
  57.     }
  58.     // Destroy the linked list to avoid memory leaks
  59.     void destroy(node* head)
  60.     {
  61.         if (head == NULL)
  62.             return;
  63.         destroy(head->next);
  64.         delete head;
  65.     }
  66. };
  67.  
  68. int main()
  69. {
  70.     linked_list a;
  71.     cout << "Adding letters from A to Z, Numbers from 0 to 25: " << endl;
  72.     char c = 'A';
  73.     for (int i = 0; i < 26; i++)
  74.     {
  75.         a.add(i, c);
  76.         c++;
  77.     }
  78.     cout << "Now the list is: " << endl;
  79.     a.display();
  80.     cout << "Destroying..." << endl;
  81.     return 0;
  82.  
  83. }
RAW Paste Data
Top