Advertisement
vaibhav1906

insert at head

Nov 27th, 2021
1,747
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 1 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node{
  5.     int val;
  6.     Node * next;
  7. };
  8.  
  9. Node * insertAtHead(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.         a->next = head;
  19.         head= a;
  20.     }
  21.    
  22.    
  23.    
  24.     return head;
  25. }
  26.  
  27. void printList(Node * head){
  28.    
  29.     while(head!=NULL){
  30.         cout<<head->val<<" ";
  31.         head= head->next;
  32.     }
  33.    
  34.     return;
  35. }
  36.  
  37. int main(){
  38.    
  39.     int n;
  40.     cout<<"How many values you want in list : "<<endl;
  41.     cin>>n;
  42.    
  43.     Node *head = NULL;
  44.    
  45.     //insertAtHead
  46.     //5
  47.     //6->5
  48.     //9->6->5
  49.    
  50.     for(int i = 0; i<n ; i++){
  51.         int data;
  52.         cout<<"Enter an integer : "<<endl;
  53.         cin>>data;
  54.        
  55.         head = insertAtHead(data,head);
  56.     }
  57.    
  58.     printList(head);
  59.    
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement