Advertisement
193030

Delete and insert from linked list

Oct 13th, 2020 (edited)
2,504
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node
  6. {
  7.     int data;
  8.     struct Node* next;
  9. } *first = NULL, *last = NULL;
  10.  
  11. void add(int x)
  12. {
  13.     if(first == NULL)
  14.     {
  15.         first = new Node;
  16.         first->data = x;
  17.         first->next = NULL;
  18.         last = first;
  19.     }
  20.     else
  21.     {
  22.         Node *t = new Node;
  23.         t->data = x;
  24.         t->next = NULL;
  25.         last->next = t;
  26.         last = t;
  27.     }
  28. }
  29.  
  30. void display (struct Node* p)
  31. {
  32.     while(p)
  33.     {
  34.         cout << p->data << " ";
  35.         p = p->next;
  36.     }
  37. }
  38.  
  39. void deleteNode (int key)
  40. {
  41.     Node* prevNode = NULL;
  42.     Node* p = first;
  43.     if(key == first->data)
  44.     {
  45.         Node *t = first;
  46.         first = first->next;
  47.         delete t;
  48.     }
  49.     else
  50.     {
  51.       while(p->data!=key)
  52.         {
  53.             prevNode = p;
  54.             p = p->next;
  55.         }
  56.     }
  57.     Node *t = p;
  58.     prevNode->next = p->next;
  59.     delete p;
  60. }
  61.  
  62. void insertAfterNode(int key, int value)
  63. {
  64.     Node *p = first;
  65.     Node *previousNode = NULL;
  66.     if(first->data == key)
  67.     {
  68.         Node *t = new Node;
  69.         t->data = value;
  70.         t->next = first->next;
  71.         first->next = t;
  72.     }
  73.     else
  74.     {
  75.         while(p->data!=key)
  76.         {
  77.             p = p->next;
  78.         }
  79.         Node *t = new Node;
  80.         t->data = value;
  81.         t->next = p->next;
  82.         p->next = t;
  83.  
  84.  
  85.       }
  86. }
  87.  
  88. int main()
  89. {
  90.  
  91.     add(24);
  92.     add(75);
  93.     add(3);
  94.     add(10);
  95.     display(first);
  96.     cout << endl;
  97.     //deleteNode(3);
  98.     insertAfterNode(24,2);
  99.     display(first);
  100. }
  101.  
Advertisement
RAW Paste Data Copied
Advertisement