Advertisement
Guest User

Untitled

a guest
Dec 18th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <vector>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <cstring>
  5.  
  6. using namespace std;
  7.  
  8. struct Node {
  9. public:
  10.     Node(int value) : value(value) {}
  11.  
  12.     int value;
  13.     Node *next;
  14. };
  15.  
  16. // первый элемент циклического списка
  17. Node* head = NULL;
  18.  
  19. // функция вставки элемента value с индексом index.
  20. void insert(int value, int index) {
  21.  
  22.     // конструируем вставляемую Node'у
  23.     Node* insertedNode = new Node(value);
  24.  
  25.     // если список пустой, то первый элемент, он же последний - само вставляемое значение
  26.     if (head == NULL) {
  27.         head = insertedNode;
  28.         head->next = head;
  29.         return;
  30.     }
  31.  
  32.     --index;
  33.     int ithElement = 0;
  34.     Node* current = head;
  35.  
  36.  
  37.     // находим куда вставлять value в спикске l (допускаем, что index < чем длина списка, то есть вставить можем всегда)
  38.     while (ithElement != index) {
  39.  
  40.         current = current->next;
  41.         ++ithElement;
  42.     }
  43.  
  44.     // до вставки на (index)-ый элемент указывал (index-1)-ый, теперь мы на место (index)-го вставляем новый, значит нужно поменять указатель на
  45.     // следующий элменет у (index-1)-го элемента, а у вставленного элемента следующим элементом указать (index)-й
  46.     //
  47.     // как было раньше:  ... -> list[index - 1] -> list[index] ->  ...
  48.     //
  49.     // как стало: ... -> list[index - 1] -> current -> list[index] -> ...  (в терминах старых индексов)
  50.     //
  51.     // в терминах новых индексов это то же самое, что и: ... -> list[index - 1] -> list[index] -> list[index + 1] (здесь list[index + 1] это list[index] из строчки выше
  52.     Node* temp = current->next;
  53.     current->next = insertedNode;
  54.     insertedNode->next = temp;
  55. }
  56.  
  57. int main() {
  58.  
  59.     insert(5, 0);
  60.     insert(6, 1);
  61.     insert(7, 1);
  62.  
  63.     Node* cur = head;
  64.     while (cur->next != head) {
  65.         cout << cur->value << " ";
  66.         cur = cur->next;
  67.     }
  68.     cout << cur->value << endl;
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement