Advertisement
raghuvanshraj

Linked Lists Basic Operations

Jun 23rd, 2021
894
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. /**
  2.  *    author:   raghuvanshraj
  3.  *    created:  23.06.2021 02:41:21 PM
  4. **/
  5. #include <bits/stdc++.h>
  6.  
  7. using namespace std;
  8.  
  9. class linked_list_node_t {
  10. public:
  11.     int data;
  12.     linked_list_node_t *next;
  13.  
  14.     linked_list_node_t(int data) {
  15.         this->data = data;
  16.         this->next = nullptr;
  17.     }
  18. };
  19.  
  20. linked_list_node_t* insert_node(linked_list_node_t *head, int pos, int data) {
  21.     linked_list_node_t *prev = nullptr;
  22.     linked_list_node_t *curr = head;
  23.     while (pos--) {
  24.         prev = curr;
  25.         curr = curr->next;
  26.     }
  27.  
  28.     linked_list_node_t *new_node = new linked_list_node_t(data);
  29.     new_node->next = curr;
  30.     if (prev != nullptr) {
  31.         prev->next = new_node;
  32.     } else {
  33.         return new_node;
  34.     }
  35.     return head;
  36. }
  37.  
  38. linked_list_node_t* delete_node(linked_list_node_t *head, int pos) {
  39.     linked_list_node_t *prev = nullptr;
  40.     linked_list_node_t *curr = head;
  41.     while (pos--) {
  42.         prev = curr;
  43.         curr = curr->next;
  44.     }
  45.  
  46.     if (prev != nullptr) {
  47.         prev->next = curr->next;
  48.     } else {
  49.         linked_list_node_t *new_head = curr->next;
  50.         delete curr;
  51.         return new_head;
  52.     }
  53.     delete curr;
  54.     return head;
  55. }
  56.  
  57. void print_linked_list(linked_list_node_t *head) {
  58.     linked_list_node_t *curr = head;
  59.     while (curr != nullptr) {
  60.         cout << curr->data << ' ';
  61.         curr = curr->next;
  62.     }
  63.     cout << endl;
  64. }
  65.  
  66. int main(int argc, char const *argv[]) {
  67.     linked_list_node_t *head = nullptr;
  68.     int T;
  69.     cin >> T;
  70.     while (T--) {
  71.         char t;
  72.         int pos, x;
  73.         cin >> t;
  74.         switch (t) {
  75.         case 'i':
  76.             cin >> pos >> x;
  77.             head = insert_node(head, pos, x);
  78.             break;
  79.  
  80.         case 'd':
  81.             cin >> pos;
  82.             head = delete_node(head, pos);
  83.             break;
  84.         }
  85.  
  86.         print_linked_list(head);
  87.     }
  88.  
  89.     delete head;
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement