Advertisement
apl-mhd

LinkedList:insert_first_positon

Feb 23rd, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. using namespace std;
  4. /*insert data in first position*/
  5. struct node{   
  6.     int data;      
  7.     struct node *link; 
  8. };
  9.  
  10.  
  11. struct node *head, *start, *root;
  12.  
  13.    
  14. void insert(int x){
  15.    
  16.     struct node *temp = new node();
  17.     //struct node *newNode = new node();
  18.    
  19.     if(head == NULL){
  20.                
  21.         temp->data = x;
  22.         temp->link = NULL;
  23.         head = temp;
  24.        
  25.         }
  26.        
  27.     else{
  28.          temp->data = x;
  29.          temp->link = NULL;
  30.         root = head;
  31.         while(root->link != NULL){
  32.        
  33.             root = root->link;
  34.         }
  35.         root->link = temp;
  36.         //head->link = temp;
  37.    
  38. }
  39.        
  40.     }
  41.    
  42. void position(){
  43.     struct node *temp = new node();
  44.     //struct node *position = new node();
  45.    
  46.     temp->data = head->data;
  47.     head->data=0;
  48.     temp->link = head->link;
  49.     head->link = temp;
  50.     //printf(" %d \n", head->link->data);
  51.    
  52.    
  53.  
  54.        
  55.    
  56. }
  57.    
  58. void print(){
  59.    
  60.     struct node *temp = head;
  61.    
  62.     printf("data:\n");
  63.    
  64.     while(temp != NULL){
  65.    
  66.         printf("%d. ",temp->data);
  67.        
  68.         temp = temp->link;
  69.        
  70.     }
  71.     printf("\n");
  72.    
  73.    
  74.     }
  75.  
  76. int main(int argc, char **argv)
  77. {
  78.      start = new node();
  79.     head = NULL;
  80.     //start = NULL;
  81.    
  82.     //int i,n;
  83.    
  84.     //for(i=0; i<10 ;i++){
  85.        
  86.         //cin>>n;
  87.         insert(1);
  88.         insert(2);
  89.         insert(3);
  90.         insert(4);
  91.         insert(5);
  92.         position();
  93.         print();
  94.            
  95.         //}
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement