代码如下
#ifndef _LinkedList_H_
#define _LinkedList_H_
using namespace std;
template <class T>
class LinkedList
{
private:
struct node
{
T data;
node* next;
node(const T& x, node* n = NULL) :data(x), next(n) {};
node() :next(NULL) { data = 0; };
};
int size;
public:
node* head;
LinkedList() :size(0)
{
head = new node;
head->next = head;
}
~LinkedList()
{
clear();
delete head;
}
node* get(int i)const
{
if (i < 0)return head;
node* p = head->next;
for (int j = 0; j < i; j++)
p = p->next;
return p;
}
int length()
{
return size;
}
void clear()
{
while (length() > 0) remove(0);
}
void insert(int i, const T& x)
{
node* p = get(i - 1);
p->next = new node(i, p->next);
size++;
}
void remove(int i)
{
cout << get(i - 1);
node* p = get(i - 1);
node* q = p->next;
p->next = q->next;
delete q;
--size;
}
int search(const T& x)const
{
node* p = head->next;
for (int i = 0; p; ++i)
{
if (x == p->data)
return i;
p = p->next;
}
return -1;
}
T visit(int i)const
{
return get(i)->data;
}
void traverse()const
{
node* p = head->next;
while (p)
{
cout << p->data << endl;
p = p->next;
}
}
void erase(int x, int y)
{
int i;
node* p = get(x - 1);
node* q = p->next;
for (i = x; i <= y; i++)
{
p->next = q->next;
delete q;
q = p->next;
--size;
}
}
class MyItr
{
friend LinkedList;
private:
node* cur;
public:
MyItr(node* p = nullptr) :cur(p) {}
MyItr operator++(int)
{
node* temp = cur;
cur = cur->next;
return temp;
}
MyItr operator++()
{
return cur = cur->next;
}
T& operator*()
{
return cur->data;
}
bool operator==(const MyItr& a)
{
return cur == a.cur;
}
bool operator!=(const MyItr& a)
{
return cur != a.cur;
}
bool IsNULL()
{
return cur == nullptr;
}
};
MyItr begin()const
{
return head;
}
void insert(MyItr& p, const T& a)
{
if (!p.cur)
{
head = p.cur = new node(a);
head->next = head;
}
else
{
p.cur = p.cur->next = new node(a, p.cur->next);
p.cur->next = head;
head = p.cur->next;
}
}
void erase(MyItr& p)
{
if (!p.cur)return;
if (p.cur->next == p.cur)
{
delete p.cur;
head = p.cur = nullptr;
}
else {
node* q;
q = p.cur->next;
p.cur = q->next;
if (q == head)head = q->next;
delete q;
}
}
MyItr search(const T& a)
{
MyItr p = begin(), q = p;
for (++p; p != q; ++p)
if (a == *p)return p;
return NULL;
}
};
#endif
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList<int>list;
LinkedList<int>::MyItr itr;
cout << "input n" << endl;
int n;
cin >> n;
itr = list.begin();
for (int i = 0; i < n; i++)
{
list.insert(itr, i+1);
cout << *itr<<" ";
}
cout << endl;
itr = list.begin();
for (int k =1; k < n; k++)
{
++itr;
++itr;
cout << "delete" << *itr << endl;
list.erase(itr);
}
cout << *itr;
return 0;
}
下面是报错截图
把 list.erase(itr); 先删除看看,因为这一行会导致迭代器状态无效