Advertisement
Guest User

list_delete_last.c

a guest
May 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.04 KB | None | 0 0
  1. // delete the last node from a linked list
  2. // 25/5/2018
  3. // Lyall Beveridge & Khye Ean Lowe
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <assert.h>
  8.  
  9. struct node {
  10.     struct node *next;
  11.     int          data;
  12. };
  13.  
  14. struct node *delete_last(struct node *head);
  15. struct node *strings_to_list(int len, char *strings[]);
  16. void print_list(struct node *head);
  17.  
  18. // DO NOT CHANGE THIS MAIN FUNCTION
  19.  
  20. int main(int argc, char *argv[]) {
  21.     // create linked list from command line arguments
  22.     struct node *head = strings_to_list(argc - 1, &argv[1]);
  23.  
  24.     struct node *new_head = delete_last(head);
  25.     print_list(new_head);
  26.  
  27.     return 0;
  28. }
  29.  
  30.  
  31. // Delete the last node in list.
  32. // The deleted node is freed.
  33. // The head of the list is returned.
  34.  
  35. struct node *delete_last(struct node *head) {
  36.     // if the head is null return null
  37.     if (head == NULL) {
  38.         return head;
  39.     } else if (head->next == NULL) {
  40.         free(head);
  41.         return NULL;
  42.     }
  43.    
  44.     struct node *current = head;
  45.     // stop on the second last actual node
  46.     while (current->next->next != NULL) {
  47.         current = current->next;
  48.     }
  49.     free(current->next);
  50.     // set the second last node to be the end
  51.     current->next = NULL;
  52.     return head;
  53. }
  54.  
  55.  
  56. // DO NOT CHANGE THIS FUNCTION
  57. // create linked list from array of strings
  58. struct node *strings_to_list(int len, char *strings[]) {
  59.     struct node *head = NULL;
  60.     for (int i = len - 1; i >= 0; i = i - 1) {
  61.         struct node *n = malloc(sizeof (struct node));
  62.         assert(n != NULL);
  63.         n->next = head;
  64.         n->data = atoi(strings[i]);
  65.         head = n;
  66.     }
  67.     return head;
  68. }
  69.  
  70. // DO NOT CHANGE THIS FUNCTION
  71. // print linked list
  72. void print_list(struct node *head) {
  73.     printf("[");
  74.  
  75.     for (struct node *n = head; n != NULL; n = n->next) {
  76.         // If you're getting an error here,
  77.         // you have returned an invalid list
  78.          printf("%d", n->data);
  79.          if (n->next != NULL) {
  80.             printf(", ");
  81.         }
  82.     }
  83.     printf("]\n");
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement