Menu
CoddyTech

removeLast

Coddy 双向链表:数据结构系列 #6 课程的第 8 课,共 14 课。

challenge icon

挑战

简单

为 DoublyLinkedList 类添加一个 removeLast 方法。

它不接收任何输入,并从列表中移除最后一个节点:

  • 如果列表为空,则不执行任何操作。
  • 否则,移除最后一个节点,更新 tail(如果列表只有一个节点,也要更新 head),并将 count 减 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)));
        }
        if (strcmp(cmd, "removeLast") == 0) DoublyLinkedList_removeLast(&ll);
    }
    return 0;
}

双向链表:数据结构系列 #6中的所有课

自己练习: C 在线编译器