rafid_shad

Delete by position Linkedlist

Mar 2nd, 2021 (edited)
680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node
  4. {
  5.     int data;
  6.     struct node *next;
  7. };
  8.  
  9.  
  10. struct node *head=NULL,*temp;
  11.  
  12.  
  13.  
  14. void delete_position(int z)
  15. {
  16.     struct node *pre,*cur;
  17.     int i=2;
  18.  
  19.     pre=head;
  20.     cur=head->next;
  21.     if(z==1)
  22.     {
  23.         head=cur;
  24.         delete(pre);
  25.     }
  26.     else
  27.     {
  28.         while(i!=z && cur->next!=NULL)
  29.         {
  30.             pre=cur;
  31.             cur=cur->next;
  32.  
  33.             i++;
  34.  
  35.         }
  36.         if(i!=z && cur->next==NULL)
  37.         {
  38.             cout<<"Position was not found in the list"<<endl;
  39.         }
  40.         else
  41.         {
  42.             pre->next=cur->next;
  43.             delete(cur);
  44.         }
  45.     }
  46.  
  47. }
  48.  
  49.  
  50.  
  51.  
  52. void display()
  53. {
  54.     temp=head;
  55.     cout<<endl;
  56.     while(temp!=NULL)
  57.     {
  58.         cout<<temp->data<<" ";
  59.         temp=temp->next;
  60.     }
  61.     cout << endl;
  62. }
  63.  
  64.  
  65. int main()
  66. {
  67.     int n,i,x;
  68.     struct node *s;
  69.     s=(struct node*)malloc(sizeof(struct node));
  70.  
  71.     cout<<"Enter how many link list u want:"<<endl;
  72.     cin>>n;
  73.  
  74.  
  75.     for(i=1; i<=n; i++)
  76.     {
  77.         struct node *newnode;
  78.         newnode=(struct node*) malloc (sizeof(struct node));
  79.         cin>>newnode->data;
  80.         newnode->next=NULL;
  81.  
  82.  
  83.  
  84.             if(head==NULL)
  85.             {
  86.                 head=newnode;
  87.                 s=head;
  88.             }
  89.  
  90.             else
  91.             {
  92.                 s->next=newnode;
  93.                 s=newnode;
  94.             }
  95.  
  96.  
  97.     }
  98.  
  99.  
  100.     cout<<"Enter a position of a note which u want to delete:"<<endl;
  101.     int z;
  102.     cin>>z;
  103.     delete_position(z);
  104.     display();
  105.  
  106.  
  107.  
  108. }
  109.  
Add Comment
Please, Sign In to add comment