Death420

C++ linked list example

Jan 19th, 2021 (edited)
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include <iostream>
  2. struct Node
  3. {
  4.   int value = 0;
  5.   Node* next = nullptr;
  6. };
  7. struct LinkedList
  8. {
  9.   Node* head = nullptr;
  10.   void add(int value){
  11.     if(head == nullptr)
  12.     {
  13.       head = new Node{value};
  14.       return;
  15.     }
  16.     Node* node = head;
  17.     while(node->next != nullptr)
  18.     {
  19.       node = node->next;
  20.     }
  21.     node->next = new Node{value};
  22.   }
  23.  
  24.   void show()
  25.   {
  26.     Node* node = head;
  27.     for(;node != nullptr; node = node->next)
  28.       std::cout << node->value << ' ';      
  29.   }
  30.   //then you'd have code for the destructor to prevent memory leaks
  31. };
  32.  
  33. int main()
  34. {  
  35.     LinkedList list;   
  36.     list.add(5);
  37.     list.add(10);
  38.     list.add(15);
  39.     list.show();   
  40. }
Add Comment
Please, Sign In to add comment