重载 DynArray 类的下标运算符,使得其可以像数组一样使用。
#include <iostream>
using namespace std;
class DynArray {
public:
DynArray();
virtual ~DynArray();
protected:
struct ArrayEle
{
int val;
ArrayEle* next;
};
private:
ArrayEle* m_head;
ArrayEle* m_tail;
ArrayEle* position(int) const;
public:
int count() const;
void add(int);
void insert(int, int);
void remove(int);
/************* begin ***************/
int& operator[](int index) const
{
return this->position(index)->val;
}
/************* end ***************/
void clear();
void print() const;
};
DynArray::DynArray()
{
this->m_head = NULL;
this->m_tail = NULL;
}
DynArray::~DynArray() {
if (m_head) this->clear();
}
typename DynArray::ArrayEle* DynArray::position(int ps) const
{
ArrayEle* p_cur = m_head;
while (ps && p_cur)
{
p_cur = p_cur->next;
ps--;
}
return p_cur;
}
int DynArray::count() const
{
if (!m_head || !m_tail)
return 0;
ArrayEle* p_tmp = m_head;
int m = 1;
while (p_tmp != m_tail)
{
p_tmp = p_tmp->next;
m++;
}
return m;
}
void DynArray::add(int v)
{
ArrayEle* p_new = new ArrayEle;
p_new->val = v;
p_new->next = NULL;
if (!m_head || !m_tail)
m_head = m_tail = p_new;
else
{
m_tail->next = p_new;
m_tail = p_new;
}
}
void DynArray::remove(int pos)
{
int ct = count();
if (pos < 0 || pos >= ct)
return;
//int ps = pos;
if (!pos)
{
ArrayEle* p_del = m_head;
m_head = m_head->next;
delete p_del;
if (ct == 1)
m_tail = NULL;
}
else
{
ArrayEle* p_tmp = this->position(pos - 1);
ArrayEle* p_del = p_tmp->next;
p_tmp->next = p_del->next;
delete p_del;
if (pos == ct - 1)
m_tail = p_tmp;
}
}
void DynArray::insert(int pos, int val)
{
int len = count();
if (pos<0 || pos>len)
return;
ArrayEle* p_new = new ArrayEle;
p_new->val = val;
p_new->next = NULL;
if (!pos)
{
if (!m_head || !m_tail)
m_head = m_tail = p_new;
else
{
p_new->next = m_head;
m_head = p_new;
}
}
else
{
ArrayEle* p_ins = position(pos - 1);
p_new->next = p_ins->next;
p_ins->next = p_new;
}
if (pos == len)
m_tail = p_new;
}
void DynArray::clear()
{
ArrayEle* p_cur = m_head;
while (p_cur)
{
ArrayEle* p_rmv = p_cur;
p_cur = p_cur->next;
delete p_rmv;
}
m_head = m_tail = NULL;
}
void DynArray::print() const
{
int len = this->count();
for (int i = 0; i < len; i++)
cout << (*this)[i] << endl;
}
/************* begin ***************/
/************* end ***************/
int main(int argc, char** argv) {
int n; // number of elements;
cin >> n;
DynArray da;
for (int i = 0; i < n; i++) {
int d;
cin >> d;
da.add(d);
}
da.insert(1, 3);
da.remove(2);
for (int i = 0; i < n; i++)
cout << da[i] << endl;
return 0;
}