Menu
Coddy logo textTech

get

Lição 7 de 14 do curso Lista Duplamente Encadeada - Série de Estruturas de Dados #6 da Coddy.

challenge icon

Desafio

Fácil

Adicione um método get à classe DoublyLinkedList.

Ele recebe um inteiro index (baseado em 0) e retorna:

  • O valor naquela posição se o índice estiver dentro da lista.
  • -1 se o índice estiver fora dos limites.

Experimente você mesmo

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "doublylinkedlist.h"

int main() {
    DoublyLinkedList ll;
    DoublyLinkedList_init(&ll);
    char line[256];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "state") == 0) printf("%s %s %d\n", ll.head == NULL ? "true" : "false", ll.tail == NULL ? "true" : "false", ll.count);
        if (strcmp(cmd, "count") == 0) printf("%d\n", ll.count);
        if (strcmp(cmd, "headValue") == 0) printf("%d\n", Node_getValue(ll.head));
        if (strcmp(cmd, "tailValue") == 0) printf("%d\n", Node_getValue(ll.tail));
        if (strcmp(cmd, "addFirst") == 0) {
            char* arg = strtok(NULL, " \t");
            DoublyLinkedList_addFirst(&ll, atoi(arg));
        }
        if (strcmp(cmd, "addLast") == 0) {
            char* arg = strtok(NULL, " \t");
            DoublyLinkedList_addLast(&ll, atoi(arg));
        }
        if (strcmp(cmd, "get") == 0) {
            char* arg = strtok(NULL, " \t");
            printf("%d\n", DoublyLinkedList_get(&ll, atoi(arg)));
        }
    }
    return 0;
}

Todas as lições de Lista Duplamente Encadeada - Série de Estruturas de Dados #6