Advertisement
Jakzon123

dll insert

Oct 15th, 2022
1,100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. template <typename T>
  2. void dll<T>::insert(T value) {
  3.     Node *node = new Node;
  4.     node->data = value;
  5.  
  6.     // Case 1: There are no nodes yet
  7.     if (head == nullptr) {
  8.         head = node;
  9.         tail = head;
  10.         return;
  11.     }
  12.  
  13.     // case 2 - inserting at the head of the list
  14.     if (node->data < head->data)
  15.     {
  16.         node->next = head;
  17.         head = node;
  18.         return;
  19.     }
  20.  
  21.     // case 3 - inserting at the end of the list
  22.     if (node->data >= tail->data)
  23.     {
  24.         node->prev = tail;
  25.         tail->next = node;
  26.         tail = node;
  27.         return;
  28.     }
  29.  
  30.     // general case - inserting into the middle
  31.     Node* probe = head;
  32.     while (probe && (node->data >= probe->data))
  33.     {
  34.         probe = probe->next;
  35.     }
  36.     if (probe)
  37.     {
  38.         node->next = probe;
  39.         node->prev = probe->prev;
  40.         probe->prev->next = node;
  41.         probe->prev = node;
  42.         return;
  43.     }
  44.  
  45.     // error - we shouldnt' reach this point. If we did, it meant the list was out of order to begin with.
  46.     return;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement