Advertisement
AlaminSakib

Linked List Implementation [BJIT]

Dec 18th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6.     int data;
  7.     struct Node *next = NULL;
  8. };
  9.  
  10. class linked_list
  11. {
  12. private:
  13.     Node *head, *tail;
  14. public:
  15.     linked_list()
  16.     {
  17.         head = NULL;
  18.         tail = NULL;
  19.     }
  20.  
  21.     void add_node(int n)
  22.     {
  23.         Node *tmp = new Node;
  24.         tmp -> data = n;
  25.         tmp -> next = NULL;
  26.  
  27.         if(head == NULL)
  28.         {
  29.             head = tmp;
  30.             tail = tmp;
  31.         }
  32.         else
  33.         {
  34.             tail -> next = tmp;
  35.             tail = tail -> next;
  36.         }
  37.     }
  38.  
  39.     void traverse()
  40.     {
  41.         Node *tmp = head;
  42.  
  43.         while(tmp != NULL)
  44.         {
  45.             if(tmp == tail) cout << tmp -> data;
  46.             else cout << tmp -> data << " -> ";
  47.             tmp = tmp -> next;
  48.         }
  49.     }
  50.  
  51.     void deletion(int n)
  52.     {
  53.         Node *tmp = head, *prev = head;
  54.  
  55.         while(tmp != NULL)
  56.         {
  57.             if(tmp -> data == n)
  58.             {
  59.                 if(tmp == head) head = head -> next;
  60.                 else if(tmp == tail) tail = prev;
  61.                 prev -> next = tmp -> next;
  62.                 return;
  63.             }
  64.             prev = tmp;
  65.             tmp = tmp -> next;
  66.         }
  67.         cout << "Element not found" << endl;
  68.     }
  69. };
  70.  
  71.  
  72. int main()
  73. {
  74.     linked_list ll;
  75.     ll.add_node(5);
  76.     ll.add_node(7);
  77.     ll.add_node(8);
  78.     ll.deletion(8);
  79.     ll.add_node(6);
  80.     ll.deletion(5);
  81.     ll.deletion(6);
  82.     ll.deletion(7);
  83.     ll.add_node(10);
  84.     ll.traverse();
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement