Advertisement
Brick

list_node

Jun 24th, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. struct list_node
  2. {
  3.     list_node* prev;
  4.     list_node* next;
  5.  
  6.     list_node()
  7.         : prev(this)
  8.         , next(this)
  9.     { }
  10.  
  11.     void link(list_node* node)
  12.     {
  13.         list_node* temp_prev = node->prev;
  14.         list_node* temp_next = next;
  15.  
  16.         node->prev = temp_next->prev;
  17.         temp_next->prev = temp_prev;
  18.  
  19.         next = temp_prev->next;
  20.         temp_prev->next = temp_next;
  21.     }
  22.  
  23.     void push_front(list_node* node)
  24.     {
  25.         link(node);
  26.     }
  27.  
  28.     void push_back(list_node* node)
  29.     {
  30.         prev->link(node);
  31.     }
  32.  
  33.     void merge(list_node* head)
  34.     {
  35.         list_node* first_value = head->next;
  36.  
  37.         if (first_value != head)
  38.         {
  39.             head->unlink();
  40.  
  41.             push_back(first_value);
  42.         }
  43.     }
  44.  
  45.     void unlink()
  46.     {
  47.         link(this);
  48.     }
  49.  
  50.     bool empty() const
  51.     {
  52.         return next == this;
  53.     }
  54.  
  55.     struct iterator
  56.     {
  57.     protected:
  58.         list_node* value;
  59.  
  60.     public:
  61.         iterator(list_node* value)
  62.             : value(value)
  63.         { }
  64.  
  65.         list_node& operator*() const
  66.         {
  67.             return *value;
  68.         }
  69.  
  70.         bool operator!=(const iterator& rhs) const
  71.         {
  72.             return rhs.value != value;
  73.         }
  74.  
  75.         iterator& operator++()
  76.         {
  77.             value = value->next;
  78.  
  79.             return *this;
  80.         }
  81.  
  82.         iterator& operator--()
  83.         {
  84.             value = value->prev;
  85.  
  86.             return *this;
  87.         }
  88.     };
  89.  
  90.     iterator begin()
  91.     {
  92.         return iterator(next);
  93.     }
  94.  
  95.     iterator end()
  96.     {
  97.         return iterator(this);
  98.     }
  99. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement