nikitast

Swap_Elements_DoublyLinkedList

Dec 29th, 2020 (edited)
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. void Swap(element*& first, element*& el1, element*& el2, element*& last)
  2. {
  3.     bool f = false;
  4.     bool l = false;
  5.     if (el1 == first)
  6.     {
  7.         element* cur = new element;
  8.         cur->prev = NULL;
  9.         cur->next = first;
  10.         first->prev = cur;
  11.         first = cur;
  12.         f = true;
  13.     }
  14.  
  15.     if (el2 == last)
  16.     {
  17.         cur = new element;
  18.         cur->next = NULL;
  19.         cur->prev = last;
  20.         last->next = cur;
  21.         last = cur;
  22.         l = true;
  23.     }
  24.  
  25.     if (el1->next == el2 || el2->next == el1)
  26.     {
  27.         el1->prev->next = el2;
  28.         el2->prev = el1->prev;
  29.  
  30.         el1->next = el2->next;
  31.         el2->next->prev = el1;
  32.  
  33.         el2->next = el1;
  34.         el1->prev = el2;
  35.     }
  36.     else
  37.     {
  38.         element* tmp1 = new element;
  39.         tmp1->next = el1->next;
  40.         tmp1->prev = el1->prev;
  41.  
  42.         element* tmp2 = new element;
  43.         tmp2->next = el2->next;
  44.         tmp2->prev = el2->prev;
  45.        
  46.         el1->prev->next = el2;
  47.         el2->prev = el1->prev;
  48.  
  49.         el1->next = el2->next;
  50.         el2->next->prev = el1;
  51.  
  52.         el1->prev = tmp2->prev;
  53.         tmp2->prev->next = el1;
  54.  
  55.         el2->next = tmp1->next;
  56.         tmp1->next->prev = el2;
  57.  
  58.         delete tmp1;
  59.         delete tmp2;
  60.     }
  61.  
  62.     if (f)
  63.     {
  64.         cur = first;
  65.         first = first->next;
  66.         first->prev = NULL;
  67.         delete cur;
  68.     }
  69.  
  70.     if (l)
  71.     {
  72.         cur = last;
  73.         last = last->prev;
  74.         last->next = NULL;
  75.         delete cur;
  76.     }
  77. }
Add Comment
Please, Sign In to add comment