Advertisement
Niloy007

Linked List Deletion

Feb 19th, 2020
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node {
  5.     int data;
  6.     struct node *next, *back;
  7. };
  8.  
  9. typedef struct node Node;
  10.  
  11. Node *start = NULL;
  12.  
  13. void showMenu() {
  14.     printf("\n1. Insert\n2. Delete\n3. Exit\n");
  15. }
  16.  
  17. void display(Node *start) {
  18.     Node *temp;
  19.     temp = start;
  20.     while(temp != NULL) {
  21.         printf("%d ", temp->data);
  22.         temp = temp->next;
  23.     }
  24.     printf("\n");
  25. }
  26.  
  27. void insertion(int item) {
  28.     Node *temp, *t;
  29.     if(start == NULL) {
  30.         start = new Node();
  31.         start->data = item;
  32.         start->next = NULL;
  33.     } else if(item <= start->data) {
  34.         temp = new Node();
  35.         temp->data = item;
  36.         temp->next = start;
  37.         start = temp;
  38.     } else {
  39.         temp = start;
  40.  
  41.         while((temp->next != NULL) && (temp->next->data < item)) {
  42.             temp = temp->next;
  43.         }
  44.  
  45.         t = new Node();
  46.         t->data = item;
  47.         t->next = temp->next;
  48.         temp->next = t;
  49.  
  50.     }
  51.  
  52. }
  53.  
  54.  
  55. void deletion(int item) {
  56.     Node *temp, *prev;
  57.     if(start->data == item) {
  58.         temp = start;
  59.         start = start->next;
  60.         delete(temp);
  61.     } else {
  62.         temp = start;
  63.         while(temp->data != item) {
  64.             prev = temp;
  65.             temp = temp->next;
  66.         }
  67.         prev->next = temp->next;
  68.         delete(temp);
  69.     }
  70. }
  71.  
  72.  
  73.  
  74.  
  75. int main() {
  76.     int choice, i = 1, item;
  77.  
  78.     do {
  79.         showMenu();
  80.         printf("Enter your choice: ");
  81.         scanf("%d", &choice);
  82.  
  83.         if(choice == 1) {
  84.             printf("Enter item to insert: ");
  85.             scanf("%d", &item);
  86.             insertion(item);
  87.             display(start);
  88.  
  89.         } else if(choice == 2) {
  90.             printf("Enter item to delete: ");
  91.             scanf("%d", &item);
  92.             deletion(item);
  93.             display(start);
  94.  
  95.         } else {
  96.             i = 0;
  97.         }
  98.     } while(i);
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement