addLast
Coddy 双向链表:数据结构系列 #6 课程的第 6 课,共 14 课。
挑战
简单为 DoublyLinkedList 类添加一个 addLast 方法。
它接收一个整数 value,并在列表的末尾插入一个携带该值的新节点。确保正确连接两个方向的链接(新节点上的 prev,旧尾节点上的 next),并且如果列表为空,则更新 head。
亲手试试
#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));
}
}
return 0;
}
双向链表:数据结构系列 #6中的所有课
自己练习: C 在线编译器