単方向連結リスト
各nodeはvalueと次nodeへのlinkを保持します。
単方向連結リストとは?
各nodeはvalueと次nodeへのlinkを保持します。
Linked listを構築、走査、破棄します。
重要なポイント
- 操作より先にinvariantを定義します。
- 空・満杯・allocation失敗を処理します。
- 計算量とownershipを一緒に評価します。
CとC++のコード例
C
main.c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
int main(void) {
Node *head = NULL;
for (int value = 3; value >= 1; --value) {
Node *node = malloc(sizeof *node);
if (!node) return 1;
*node = (Node){value, head};
head = node;
}
while (head) {
Node *next = head->next;
printf("%d ", head->value);
free(head);
head = next;
}
puts("");
return 0;
}
1 2 3
C++
main.cpp
#include <iostream>
#include <memory>
struct Node {
int value;
std::unique_ptr<Node> next;
};
int main() {
std::unique_ptr<Node> head;
for (int value = 3; value >= 1; --value) {
head = std::make_unique<Node>(Node{value, std::move(head)});
}
for (Node *node = head.get(); node; node = node->next.get()) {
std::cout << node->value << ' ';
}
std::cout << '\n';
}
1 2 3
CとC++の比較
Cはmallocした各nodeをfreeします。C++ unique_ptrはhead破棄時にchain全体を自動解放します。
C
構造体と操作は分離され、allocationは明示的です。
C++
classとcontainerがinvariantとresourceを管理します。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- 空と容量境界をテストします。
- cleanupを実装しleakを確認します。
- standard containerと比較します。