Lớp Node
Bài học 3 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ễViết một lớp Node gồm:
- Một hàm khởi tạo nhận một số nguyên
value. Lưu giá trị này vào một trường của lớp và khởi tạo cảprevlẫnnextthànhnull(hoặc giá trị tương đương trong ngôn ngữ của bạn). - Một phương thức
getValuekhông nhận đầu vào và trả vềvalueđã lưu.
Tự làm thử
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "node.h"
int main() {
Node* node = NULL;
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, "create") == 0) {
char* arg = strtok(NULL, " \t");
if (arg) node = Node_new(atoi(arg));
}
if (strcmp(cmd, "getValue") == 0) {
printf("%d\n", Node_getValue(node));
}
if (strcmp(cmd, "nextIsNull") == 0) {
printf("%s\n", node->next == NULL ? "true" : "false");
}
if (strcmp(cmd, "prevIsNull") == 0) {
printf("%s\n", node->prev == NULL ? "true" : "false");
}
}
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