Advertisement
Vladpepe

Untitled

Oct 25th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. // Insert any number at beginning of the linked list implementation
  2.  
  3.  
  4. #define _CRT_SECURE_NO_WARNINGS
  5. #include "stdlib.h"
  6. #include "stdio.h"
  7.  
  8. struct Node {                   // define the struct type
  9.     int data;                   // the Node struct is composed by firs part that contain the data as intiger
  10.     struct Node* next;          // the secondo part contain the adress of the next Node
  11. };
  12.  
  13. struct Node* head;               // global variable,can be accessed anywhere
  14.  
  15. void Insert(int x) {            // insert at the beginning
  16.  
  17.     struct Node* temp = malloc(sizeof(struct Node));   // alloc enough memory for a temp struct Node
  18.     temp->data = x;                                     // the data part of the Node contain the number that we want to insert at the beginning
  19.     temp->next = head;                                  //and put the adress of the old head in the next adress, it's like shifting to the right all the list
  20.     head = temp;                                        //now the new head is our inserted element
  21. }
  22.  
  23. void Print() {
  24.     struct Node* temp = head;                   //begin to print from the head, it's like the root of the list
  25.     printf("List is :  ");                     
  26.     while (temp != NULL) {                      // while the adress of the next inside the current Node is not empty, print all the temp->data
  27.         printf(" %d", temp->data);
  28.         temp = temp->next;
  29.     }
  30.     printf("\n");
  31. }
  32.  
  33.  
  34.  
  35. int main() {
  36.     head = NULL;                         // empty list;
  37.     printf("how many numbers?\n");
  38.         int n ,i,x;
  39.     scanf("%d", &n);                     //save inside a variable our number in input
  40.  
  41.     for (i = 0;i < n; i++) {             // insert all the number in the beginning of the list  
  42.         printf("enter the number \n");
  43.         scanf("%d", &x);               
  44.         Insert(x);                       //insert function     
  45.         Print();
  46.  
  47.  
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement