Menu
Coddy logo textTech

remove

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

challenge icon

Desafio

Fácil

Adicione um método remove à classe LinkedList.

Ele recebe um inteiro index (baseado em 0):

  • Se o índice apontar para um nó existente, remova esse nó da lista e decremente count.
  • Se o índice estiver fora do intervalo, não faça nada.

Experimente você mesmo

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

int main() {
    LinkedList ll;
    LinkedList_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 %d\n", ll.head == 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, "addFirst") == 0) {
            char* arg = strtok(NULL, " \t");
            LinkedList_addFirst(&ll, atoi(arg));
        }
        if (strcmp(cmd, "addLast") == 0) {
            char* arg = strtok(NULL, " \t");
            LinkedList_addLast(&ll, atoi(arg));
        }
        if (strcmp(cmd, "get") == 0) {
            char* arg = strtok(NULL, " \t");
            printf("%d\n", LinkedList_get(&ll, atoi(arg)));
        }
        if (strcmp(cmd, "remove") == 0) {
            char* arg = strtok(NULL, " \t");
            LinkedList_remove(&ll, atoi(arg));
        }
    }
    return 0;
}

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