addLast
Coddy 链表:数据结构系列第 5 课 课程的第 6 课,共 14 课。
挑战
简单为 LinkedList 类添加一个 addLast 方法。
它接收一个整数 value,并在列表的末尾插入一个携带该值的新节点。将 count 加 1。
亲手试试
#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));
}
}
return 0;
}
链表:数据结构系列第 5 课中的所有课
自己练习: C 在线编译器