温故知新:
以前学习c++时写的链表
复习一下
#include <iostream>
using namespace std;
template<typename T=int>
class List
{
private:
struct Node
{
T data;
Node* next;
Node(const T& d):data(d),next(NULL){}
};
Node* head;
int n;
public:
List():head(NULL),n(0)
{ }
void clear()
{
Node* p = head;
while(p)
{
Node* q = p->next;
delete p;
p = q;
}
head = NULL;
n = 0;
}
~List()
{
clear();
}
void travel()const
{
Node* p = head;
while( p )
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
Node* & getp(int pos)//按索引查找
{
if(pos<0||pos>n)
pos=n;//throw xxx;
if(pos==0)
return head;
Node* p = head;
for(int i=1; i<pos; i++)// i 为索引,i等于几,p 就指向对应的那个位置
p = p->next;
return p->next;
}
Node* const & getp(int pos)const
{
return const_cast<List*>(this)->getp(pos);
}
void insert(const T& d, int pos=-1)
{
Node* & r = getp(pos);
Node* p = new Node(d);
p->next = r;
r = p;
++n;
}
int find(const T& d, int pos=0)const
{
Node* p = getp(pos);
while(p)
{
if(p->data==d)
return pos;//找到了
p = p->next;
++pos;
}
return -1;//没找到
}
bool erase(const T& d, int pos=0)
{
if( (pos=find(d,pos))==-1 )
return false;//没找到
Node* & r = getp(pos);
Node* p = r;
r = r->next;
delete p;
p = NULL;
--n;
return true;
}
bool update(const T& oldd, const T& newd, int pos=0)
{
if( (pos=find(oldd,pos))==-1 )
return false;//没找到
getp(pos)->data = newd;
return true;
}
int size()const
{
return n;
}
bool empty()const
{
return n==0;
}
const T& front()const throw(int)
{
if(empty())
throw 1;
return head->data;
}
const T& back()const throw(int)
{
if(empty())
throw 2;
return getp(n-1)->data;
}
void push_front(const T& d)
{
insert(d,0);
}
void push_back(const T& d)
{
insert(d);
}
};