Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | None | 0 0
  1. //Write a function that appends a new node containing int i at the end of a singly linked list.
  2.  
  3. #include <stdbool.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. #define SIZE 10
  8.  
  9. typedef struct node
  10. {
  11.     // the n to store in this node
  12.     int n;
  13.  
  14.     // the link to the next node in the list
  15.     struct node* next;
  16. }
  17. node;
  18.  
  19. node* head = NULL;
  20.  
  21. void append(int i)
  22. {
  23.     node *newNode = malloc(sizeof(node));
  24.  
  25.     if(newNode == NULL)
  26.     {
  27.         fprintf(stderr, "Unable to allocate memory for new node\n");
  28.         exit(-1);
  29.     }
  30.  
  31.     newNode->n = i;
  32.     newNode->next = NULL;  // Change 1
  33.  
  34.     //check for first insertion
  35.     if(head->next == NULL)
  36.     {
  37.         head->next = newNode;
  38.     }
  39.  
  40.     else
  41.     {
  42.         //else loop through the list and find the last
  43.         //node, insert next to it
  44.         node *current = head;
  45.         while (true) { // Change 2
  46.             if(current->next == NULL)
  47.             {
  48.                 current->next = newNode;
  49.                 printf("added later\n");
  50.                 break; // Change 3
  51.             }
  52.             current = current->next;
  53.         };
  54.     }
  55. }
  56.  
  57. int main(void)
  58. {
  59.     // creating list
  60.     printf("Appending ints 0-%i onto the list...\n", SIZE - 1);
  61.     for (int i = 0; i < SIZE; i++)
  62.     {
  63.         append(i);
  64.     }
  65.     printf("done!\n");
  66.  
  67.     // printing out list
  68.     printf("Your list contains ");
  69.     for (node*  ptr = head; ptr != NULL; ptr = ptr->next)
  70.     {
  71.         printf("%i ", ptr->n);
  72.     }
  73.     printf("\n");
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement