COMP1721 - Higher Computing 1B

Computing 1B - Week 09 Tutorial Solutions

  1. Recursive:
    /*
     * return true iff value occurs in list
     */
    int
    member(int value, linked_list list) {
    	return list != NULL && (list->data == value || member(value, list->next));
    }
    
    Iterative:
    /*
     * return true iff value occurs in list
     */
    int
    member(int value, linked_list list) {
    	list_node *n;
    	for (n = list; n != NULL; n = n->next)
    		if (n->data == value)
    			return 1;
    	return 0;
    }
    

  2. /*
     * convert string to a linked list
     */
    linked_list
    string_to_list(char *s) {
        char *t;
        linked_list list = NULL;
        while (*s != '\0') {
            int i = strtol(s, &t, 10);
            if (s != t) {
                /*
                 * parsed an int from string
                 * add to list
                 */
                list = append(i, list);
                s = t;
                continue;
            }
            s++;
        }
        return list;
    }
    

  3. /*
     * convert list to malloc'ed string
     */
    char *
    list_to_string(linked_list list) {
        char      buffer[32]; /* must be big enough to hold the largest int */
        list_node *n;
        char      *s, *t;
        int       n_chars;
        
        n_chars = 3;  /* [] and '\0' */
        for (n = list; n != NULL; n = n->next) {
            sprintf(buffer, "%d", n->data);
            n_chars += strlen(buffer);
            if (n->next != NULL)
                n_chars += 2;  /* ", " */
        }
        s = malloc(n_chars);
        if (s == NULL) {
            fprintf(stderr, "out of memory\n");
            exit(1);
        }
        t = s;
        *t = '[';
        t++;
        for (n = list; n != NULL; n = n->next) {
            sprintf(t, "%d", n->data);
            t += strlen(t);
            
            if (n->next != NULL) {
                strcat(t, ", ");
                t += 2;  /* ", " */
            }
        }
        *t = ']';
        t++;
        *t = '\0';
        return s;
    }
    


Andrew Taylor (andrewt@cse.unsw.edu.au)
Higher Computing 1B, Computer Science & Engineering, UNSW