Advertisement
Vladpepe

Untitled

Oct 25th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.75 KB | None | 0 0
  1. //insertion at nth position on the linked list
  2.  
  3. #define _CRT_SECURE_NO_WARNINGS
  4.  
  5. #include "stdlib.h"
  6. #include "stdio.h"
  7.  
  8. struct Node {                   //define de Node struct
  9.     int data;                   // it's composed of a part that contain the data of the current node and the adress of the next node
  10.     struct Node* next;
  11. };
  12.  
  13. struct Node* head;  // global variable so we can access from all the function
  14.  
  15. void Insert(int data, int n) {
  16.  
  17.     struct Node* temp1 = malloc(sizeof(struct Node*));              //dynamic alloc memory for a Node type 
  18.     temp1->data = data;                                             //store the data that we want on the data box of the struct
  19.     temp1->next = NULL;                                             // in the adress of the next Node we put a Null adress so this will be the last element for now
  20.  
  21.     if (n == 1) {                           //if we want to place the number in the first place, we have to put the old head of the list as next node adress, so our insertion will be at the beginning
  22.         temp1->next = head;
  23.         head = temp1;                       //set the new inserted Node as head
  24.         return;                             //and it's done
  25.     }
  26. struct  Node* temp2 = head;                     // else create a new node that contain the old head
  27. for (int i = 0; i < n - 2; i++) {               //scroll all the node while the position is != of where we want to insert
  28.     temp2 = temp2->next;
  29. }
  30. temp1->next = temp2->next;                      //when we found the position where to insert our temp1
  31. temp2->next = temp1;
  32.  
  33. }
  34.  
  35. void Print() {
  36.     struct Node* temp = head;               //start from the head, while the list is != empty print all the data
  37.     while (temp != NULL) {
  38.         printf("%d", temp->data);
  39.         temp = temp->next;
  40.     }
  41.     printf("\n");
  42. }
  43.  
  44.  
  45. int main() {                                               
  46.     head = NULL;  // empty list
  47.     Insert(1, 1);                       //insert the number 1 on the position 1 of the list
  48.     Insert(2, 2);
  49.     Insert(3, 3);
  50.     Insert(4, 2);
  51.     Print();
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement