get
Coddy의 이중 연결 리스트 - 자료구조 시리즈 #6 코스 레슨 — 14개 중 7번째.
챌린지
쉬움DoublyLinkedList 클래스에 get 메서드를 추가하세요.
이 메서드는 정수 index (0부터 시작)를 인자로 받아 다음을 반환합니다:
- 인덱스가 리스트 범위 내에 있으면 해당 위치의 값을 반환합니다.
- 인덱스가 범위를 벗어나면
-1을 반환합니다.
직접 해보기
#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;
}