Sebgg

l2u4/5

Nov 12th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. struct Node
  2. {
  3.   Node(int _value = 0, Node* _next = nullptr)
  4.    : value{_value}, next{_next}
  5.   {
  6.   }
  7.  
  8.   void set_next(Node* _next)
  9.   {
  10.     next = _next;
  11.   }
  12.  
  13.   int value;
  14.   Node* next;
  15. };
  16.  
  17. struct List
  18. {
  19.   List()
  20.    : first{nullptr}
  21.   {
  22.   }
  23.  
  24.   void add_node(int value)
  25.   {
  26.  
  27.     if(first == nullptr)
  28.     {
  29.       Node* _new{new Node{value}};
  30.       first = _new;
  31.     }
  32.     else if(first->value > value)
  33.     {
  34.       Node* _new{new Node{value, first}};
  35.       first = _new;
  36.     }
  37.     else
  38.     {
  39.       Node* curr{first};
  40.  
  41.       while(curr->next != nullptr)
  42.       {
  43.         if(curr->next->value < value)
  44.         {
  45.           curr = curr->next;
  46.         }
  47.         else
  48.         {
  49.           break;
  50.         }
  51.       }
  52.       Node* _new{new Node{value, curr->next}};
  53.       curr->next = _new;
  54.     }
  55.   }
  56.  
  57.   Node* first;
  58. };
  59.  
  60.  
  61. int main()
  62. {
  63.   List l{};
  64.  
  65.   l.add_node(5);
  66.   l.add_node(9);
  67.   l.add_node(8);
  68.  
  69.   std::cout << l.first->value << std::endl;
  70.   std::cout << l.first->next->value << std::endl;
  71.   //std::cout << l.first->next->next->value << std::endl;
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment