Advertisement
Niloy007

Linked List Insertion

Feb 19th, 2020
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 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.  
  56. int main() {
  57.     int choice, i = 1, item;
  58.  
  59.     do {
  60.         showMenu();
  61.         printf("Enter your choice: ");
  62.         scanf("%d", &choice);
  63.  
  64.         if(choice == 1) {
  65.             printf("Enter item to insert: ");
  66.             scanf("%d", &item);
  67.             insertion(item);
  68.             display(start);
  69.  
  70.         } else if(choice == 2) {
  71.  
  72.         } else {
  73.             i = 0;
  74.         }
  75.     } while(i);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement