-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMap.h
133 lines (111 loc) · 1.79 KB
/
Map.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
#pragma once
#include <iostream>
using namespace std;
template <class _Key, class _Value> class Map
{
private:
struct node
{
public:
node* next;
_Key key;
_Value val;
node(const _Key k) : next(nullptr) { key = k; };
~node() { delete next; }
node(const node& s) : next(nullptr)
{
key = s.key;
val = s.val;
};
private:
node& operator=(const node&);
};
node* head;
node* nodeFind(const _Key key) const
{
node* c = head;
while (c) {
if (key == c->key)
{
return c;
}
c = c->next;
};
return nullptr;
}
void clear()
{
while (head)
{
node* t = head->next;
delete head;
head = t;
}
}
void swap(Map& m)
{
node* t = head;
head = m.head;
m.head = t;
}
public:
Map() { head = nullptr; }
Map(const Map& m)
{
node *source, **destination;
head = NULL;
source = m.head;
destination = &head;
while (source)
{
*destination = new node(*source);
source = source->next;
destination = &((*destination)->next);
}
}
~Map() { delete head; }
Map& operator=(const Map& m)
{
if (&m == this) {
return *this;
}
Map t(m);
swap(t);
return *this;
}
_Value* find(const _Key& key)
{
node* c = nodeFind(key);
if (!c)
{
c = head;
}
return &c->val;
}
void add(const _Key& key, const _Value& value)
{
node* newnode = nodeFind(key);
if (!newnode)
{
newnode = new node(key);
newnode->next = head;
head = newnode;
head->val = value;
}
else
{
newnode->val = value;
}
}
friend ostream& operator<<(ostream& out, const Map& m)
{
node* itr = m.head;
while (itr)
{
out << "Key: " << itr->key << "\t";
out << "Value: " << itr->val << "\n";
itr = itr->next;
}
return out;
}
};