Advertisement
vaibhav1906

Insert at Tail and deletion

Nov 27th, 2021
2,046
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node{
  5.     int val;
  6.     Node * next;
  7. };
  8.  
  9. Node * insertAtTail(int data,Node* head){
  10.     Node * a = new Node();
  11.     a->val = data;
  12.     a->next = NULL;
  13.    
  14.     if(head==NULL){
  15.         head = a;
  16.     }
  17.     else{
  18.        
  19.         Node * temp = head;
  20.        
  21.         while(temp->next!=NULL){
  22.             temp = temp->next;
  23.         }
  24.        
  25.         temp->next = a;
  26.        
  27.     }
  28.    
  29.    
  30.     return head;
  31. }
  32.  
  33. void printList(Node * head){
  34.    
  35.     while(head!=NULL){
  36.         cout<<head->val<<" ";
  37.         head= head->next;
  38.     }
  39.    
  40.     return;
  41. }
  42.  
  43. Node * delNode(Node * head, int d){
  44.    
  45.     Node * temp = head;
  46.    
  47.     if(head->val == d){
  48.         head = head->next;
  49.         return head;
  50.     }
  51.    
  52.     while( temp->next!=NULL && temp->next->val!=d){
  53.         temp = temp->next;
  54.     }
  55.    
  56.     if(temp->next!=NULL){
  57.         temp->next = temp->next->next;
  58.     }
  59.  
  60.    
  61.     return head;
  62. }
  63.  
  64. int main(){
  65.    
  66.     int n;
  67.     cout<<"How many values you want in list : "<<endl;
  68.     cin>>n;
  69.    
  70.     Node *head = NULL;
  71.    
  72.     //5->6->9
  73.     for(int i = 0; i<n ; i++){
  74.         int data;
  75.         cout<<"Enter an integer : "<<endl;
  76.         cin>>data;
  77.        
  78.         head = insertAtTail(data,head);
  79.     }
  80.    
  81.    
  82.     printList(head);
  83.    
  84.  
  85.     //5->6->3->8->11
  86.    
  87.     int d;
  88.     cout<<"Value you want to delete from list : "<<endl;
  89.     cin>>d;
  90.     head = delNode(head,d);
  91.    
  92.     printList(head);
  93.     //5->6->8->11 (if d is 3)
  94.    
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement