fork download
  1. #include <iostream>
  2. #include <initializer_list>
  3.  
  4. struct Node
  5. {
  6. char data;
  7. Node* next_node = nullptr;
  8. Node(const char& a) // create a constrcor which will initilize data
  9. : data(a) {} // at the time of Node creation
  10. };
  11.  
  12. namespace mylib{
  13. class list
  14. {
  15. private:
  16. Node *head = nullptr; // need only head, if it's a simple list
  17. public:
  18. list() :head(nullptr) {} // constructor set it to nullptr
  19. list(std::initializer_list<int> arr) // initilizer list constructor
  20. {
  21. for(const auto& it: arr)
  22. this->insert(it);
  23. }
  24. ~list()
  25. {
  26. Node* temp = head;
  27. while( temp != nullptr )
  28. {
  29. Node* next = temp->next_node;
  30. delete temp;
  31. temp = next;
  32. }
  33. head = nullptr;
  34. }
  35.  
  36.  
  37. void insert(const char& value)
  38. {
  39. if(head == nullptr) // first case
  40. {
  41. Node *newNode = new Node(value);
  42. newNode->next_node = head;
  43. head = newNode;
  44. }
  45. else // all new nodes
  46. {
  47. Node *temp = head;
  48. while(temp->next_node != nullptr) // to find the null point (end of list)
  49. temp = temp->next_node;
  50.  
  51. temp = temp->next_node = new Node(value);
  52. }
  53. }
  54.  
  55. void print() const // just to print
  56. {
  57. Node *temp = head;
  58. while(temp != nullptr)
  59. {
  60. std::cout << temp->data << "\n";
  61. temp = temp->next_node;
  62. }
  63. }
  64. };
  65. }
  66.  
  67. int main()
  68. {
  69. mylib::list myList = {'a', 'b', 'c' , 'a' };
  70.  
  71. myList.print();
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0s 4404KB
stdin
Standard input is empty
stdout
a
b
c
a