addFirst
Bài học 5 trên 14 trong khóa học Danh sách liên kết kép, chuỗi cấu trúc dữ liệu #6 của Coddy.
Thử thách
DễThêm phương thức addFirst vào lớp DoublyLinkedList.
Phương thức nhận một số nguyên value và chèn một nút mới chứa giá trị đó vào đầu danh sách. Hãy nối liên kết theo cả hai hướng (prev trên nút đầu cũ, next trên nút mới) và cập nhật tail nếu danh sách đang rỗng.
Tự làm thử
#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));
}
}
return 0;
}
Tất cả bài học trong Danh sách liên kết kép, chuỗi cấu trúc dữ liệu #6
Tự luyện tập: Trình biên dịch C online