forked from drken1215/book_algorithm_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_8_4.cpp
More file actions
65 lines (54 loc) · 1.58 KB
/
code_8_4.cpp
File metadata and controls
65 lines (54 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 連結リストの各ノードを表す構造体
struct Node {
Node* next; // 次がどのノードを指すか
string name; // ノードに付随している値
Node(string name_ = "") : next(NULL), name(name_) { }
};
// 番兵を表すノードをグローバル領域に置いておく
Node* nil;
// 初期化
void init() {
nil = new Node();
nil->next = nil; // 初期状態では nil が nil を指すようにする
}
// 連結リストを出力する
void printList() {
Node* cur = nil->next; // 先頭から出発
for (; cur != nil; cur = cur->next) {
cout << cur->name << " -> ";
}
cout << endl;
}
// ノード p の直後にノード v を挿入する
// ノード p のデフォルト引数を nil としておく
// そのため insert(v) を呼び出す操作は,リストの先頭への挿入を表す
void insert(Node* v, Node* p = nil) {
v->next = p->next;
p->next = v;
}
int main() {
// 初期化
init();
// 作りたいノードの名前の一覧
// 最後尾のノード (「山本」) から順に挿入することに注意
vector<string> names = {"yamamoto",
"watanabe",
"ito",
"takahashi",
"suzuki",
"sato"};
// 各ノードを生成して,連結リストの先頭に挿入していく
for (int i = 0; i < (int)names.size(); ++i) {
// ノードを作成する
Node* node = new Node(names[i]);
// 作成したノードを連結リストの先頭に挿入する
insert(node);
// 各ステップの連結リストの様子を出力する
cout << "step " << i << ": ";
printList();
}
}