remove
Coddy의 연결 리스트 - 자료구조 시리즈 #5 코스 레슨 — 14개 중 8번째.
챌린지
쉬움LinkedList 클래스에 remove 메서드를 추가하세요.
이 메서드는 정수형 index (0부터 시작)를 매개변수로 받습니다:
- 만약 인덱스가 기존 노드를 가리키고 있다면, 해당 노드를 리스트에서 제거하고
count를 감소시킵니다. - 만약 인덱스가 범위를 벗어나면, 아무것도 하지 않습니다.
직접 해보기
#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;
}