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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
|
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
struct Person
{
Person(string name, int age) : name(name), age(age)
{
}
string Stringify()
{
ostringstream oss;
oss << name << "(" << age << ")";
return oss.str();
}
string Verbose()
{
ostringstream oss;
oss << "[" << Stringify() << " ";
if (prev)
oss << "prev:"<<prev->Stringify() << " ";
if (next)
oss << "next:"<<next->Stringify();
oss << "] ";
return oss.str();
}
string name;
int age;
Person* prev;
Person* next;
};
class PersonManager
{
public:
PersonManager() : size_(0)
{
}
// Deallocate memory
~PersonManager()
{
CleanUp();
}
// Add as a new head
//TODO: possibly check for unique names (same for Append)
void InsertFront(string name, int age)
{
Person* p = new Person(name, age);
if (!head_)
{
head_ = p;
tail_ = p;
}
else
{
head_->prev = p;
p->next = head_;
head_ = p;
}
size_ += 1;
}
// Appends to the back
void Append(string name, int age)
{
Person* p = new Person(name, age);
if (!head_)
{
head_ = p;
tail_ = p;
}
else
{
tail_->next = p;
p->prev = tail_;
tail_ = p;
}
size_ += 1;
}
size_t Size()
{
return size_;
}
void Show(bool verbose=false)
{
if (!head_)
{
cout << "List is empty.\n";
}
else
{
Person* p = head_;
while(p)
{
if (verbose)
cout << p->Verbose() << endl;
else
cout << p->Stringify() << endl;
p = p->next;
}
cout << endl;
}
}
// Delete all nodes
void CleanUp()
{
Person* p = head_;
Person* tmp;
while(p)
{
tmp = p->next;
delete p;
p = tmp;
}
head_ = nullptr;
tail_ = nullptr;
size_ = 0;
}
private:
Person* head_;
Person* tail_;
size_t size_;
};
int main()
{
PersonManager pm;
vector<pair<string,int>> people =
{
{ "John Doe", 30 },
{ "Loren Zimmerman", 55 },
{ "Rodney Vega", 43 },
{ "Raquel Cannon", 15 },
{ "Lynette Bush", 10 },
{ "Perry Carr", 37 },
{ "Judy Richardson", 45 },
{ "Juanita Andrews", 31 },
{ "Olive Shelton", 57 },
{ "Ervin Warren", 29 },
{ "Jana Bradley", 13 },
{ "Jane Doe", 28 }
};
// First half appended to back
for (int i=0; i<=people.size()/2 - 1; ++i)
pm.Append(people[i].first, people[i].second);
// Second half inserted to the front
for (int i=people.size()/2; i<people.size(); ++i)
pm.InsertFront(people[i].first, people[i].second);
cout << "List of size " << pm.Size() << endl;
pm.Show();
return 0;
}
|