removeLast
Coddyの「双方向連結リスト - データ構造シリーズ #6」コースのレッスン 8/14。
チャレンジ
簡単DoublyLinkedList クラスに removeLast メソッドを追加してください。
このメソッドは入力を受け取らず、リストから最後のノードを削除します。
- リストが空の場合は、何もしません。
- それ以外の場合は、最後のノードを削除し、
tailを更新します(リストにノードが1つしかなかった場合はheadも更新します)。そしてcountをデクリメントします。
自分で試してみよう
#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)));
}
if (strcmp(cmd, "removeLast") == 0) DoublyLinkedList_removeLast(&ll);
}
return 0;
}