mirror of
				https://github.com/sloven-c/linked_list.git
				synced 2025-11-04 06:57:25 +01:00 
			
		
		
		
	Display n-th element in the list
This commit is contained in:
		
							
								
								
									
										40
									
								
								main.c
									
									
									
									
									
								
							
							
						
						
									
										40
									
								
								main.c
									
									
									
									
									
								
							@@ -14,12 +14,28 @@ void rem(struct List **list, int value_to_remove);
 | 
			
		||||
 | 
			
		||||
void print_list(const struct List *list);
 | 
			
		||||
 | 
			
		||||
int *get(const struct List *list, int n);
 | 
			
		||||
 | 
			
		||||
int llen(const struct List *list);
 | 
			
		||||
 | 
			
		||||
int main(void) {
 | 
			
		||||
    struct List *seznam = init(1);
 | 
			
		||||
    add(seznam, 5);
 | 
			
		||||
    add(seznam, 2);
 | 
			
		||||
    print_list(seznam);
 | 
			
		||||
 | 
			
		||||
    constexpr int n = 2;
 | 
			
		||||
    int *get_n = get(seznam, n);
 | 
			
		||||
    printf("Attempting to find %d. element => ", n);
 | 
			
		||||
    if (get_n == NULL) {
 | 
			
		||||
        // element doesn't exist
 | 
			
		||||
        printf("failed!");
 | 
			
		||||
    } else {
 | 
			
		||||
        printf("succeeded. Value = %d", *get_n);
 | 
			
		||||
        free(get_n);
 | 
			
		||||
    }
 | 
			
		||||
    printf("\n\n");
 | 
			
		||||
 | 
			
		||||
    rem(&seznam, 1);
 | 
			
		||||
    print_list(seznam);
 | 
			
		||||
 | 
			
		||||
@@ -102,3 +118,27 @@ void print_list(const struct List *list) {
 | 
			
		||||
    }
 | 
			
		||||
    printf("\n");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// we will pretend the user is not a programmer and enters n=1 for first element and so on
 | 
			
		||||
int *get(const struct List *list, const int n) {
 | 
			
		||||
    const int list_len = llen(list);
 | 
			
		||||
    if (n > list_len || n <= 0) return nullptr;
 | 
			
		||||
 | 
			
		||||
    for (int i = 0; i < n - 1; i++) {
 | 
			
		||||
        list = list->next;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    int *val = malloc(sizeof(int));
 | 
			
		||||
    *val = list->value;
 | 
			
		||||
    return val;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
int llen(const struct List *list) {
 | 
			
		||||
    int len = 0;
 | 
			
		||||
 | 
			
		||||
    for (; list != NULL; list = list->next) {
 | 
			
		||||
        len++;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    return len;
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user