-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathSequenceST.h
executable file
·134 lines (111 loc) · 2.65 KB
/
SequenceST.h
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
//
// Created by light on 19-9-2.
//
#ifndef ALG_SEQUENCEST_H
#define ALG_SEQUENCEST_H
#include <iostream>
#include <cassert>
#include "../interface.h"
using namespace std;
// 顺序查找表实现
template<typename Key, typename Value>
class SequenceST {
private:
struct Node {
Key key;
Value value;
Node *next;
Node(Key key, Value value) {
this->key = key;
this->value = value;
this->next = NULL;
}
};
Node *head; // 表头
int count; // 顺序查找表中的节点数
public:
// 构造函数
SequenceST() {
head = NULL;
count = 0;
}
// 析构函数
~SequenceST() {
while (head) {
Node *node = head;
head = head->next;
delete node;
count--;
}
assert(head == NULL && count == 0);
}
int size() {
return count;
}
bool isEmpty() {
return count == 0;
}
void insert(Key key, Value value) {
Node *node = head;
while (node) {
if (key == node->key) {
node->value = value;
return;
}
node = node->next;
}
Node *newNode = new Node(key, value);
newNode->next = head;
head = newNode;
count++;
}
void set(Key key, Value value) {
Node *node = head;
while (node) {
if (key == node->key) {
node->value = value;
return;
}
node = node->next;
}
}
bool contain(Key key) {
Node *node = head;
while (node) {
if (key == node->key)
return true;
node = node->next;
}
return false;
}
Value *search(Key key) {
Node *node = head;
while (node) {
if (key == node->key)
return &node->value;
node = node->next;
}
return NULL;
}
Value *remove(Key key) {
if (head == NULL) return nullptr;
// 第一个节点就满足删除节点条件,保留后继节点并删除当前节点
if (key == head->key) {
Node *delNode = head;
head = head->next;
count--;
return &delNode->value;
}
Node *node = head;
while (node->next && node->next->key != key) {
node = node->next;
}
if (node->next) {
Node *delNode = node->next;
node->next = delNode->next;
count--;
return &delNode->value;
}
}
};
#endif //ALG_SEQUENCEST_H