Advertisement
Guest User

list_contains.c

a guest
Apr 5th, 2020
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4.  
  5. struct node {
  6.     struct node *next;
  7.     int          data;
  8. };
  9.  
  10. int contains(int value, struct node *head);
  11. struct node *strings_to_list(int len, char *strings[]);
  12.  
  13. // DO NOT CHANGE THIS MAIN FUNCTION
  14.  
  15. int main(int argc, char *argv[]) {
  16.     int value;
  17.     scanf("%d", &value);
  18.     // create linked list from command line arguments
  19.     struct node *head = NULL;
  20.     if (argc > 1) {
  21.         // list has elements
  22.         head = strings_to_list(argc - 1, &argv[1]);
  23.     }
  24.  
  25.     int result = contains(value, head);
  26.     printf("%d\n", result);
  27.  
  28.     return 0;
  29. }
  30.  
  31. // Return 1 if value occurs in linked list, 0 otherwise
  32. int contains(int value, struct node *head) {
  33.     int found = 0;
  34.     while (head != NULL) {
  35.         if (head->data == value) {
  36.             found = 1;
  37.         }
  38.         head = head->next;
  39.     }
  40.    
  41.     return found;
  42.  
  43. }
  44.  
  45.  
  46. // DO NOT CHANGE THIS FUNCTION
  47. // create linked list from array of strings
  48. struct node *strings_to_list(int len, char *strings[]) {
  49.     struct node *head = NULL;
  50.     int i = len - 1;
  51.     while (i >= 0) {
  52.         struct node *n = malloc(sizeof (struct node));
  53.         assert(n != NULL);
  54.         n->next = head;
  55.         n->data = atoi(strings[i]);
  56.         head = n;
  57.         i -= 1;
  58.     }  
  59.     return head;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement