前2个月帮别人写的List的实现

作者在 2006-10-25 16:44:00 发布以下内容

我本来打算把它做成和STL一样的模板。想把STL上学的知识用用。
加迭代器,以及typedef typename iterator_trains<TYPE>::value_type value_type;
但是一直都痴迷于MFC程序和网络编程去了,所以就耽误了,以后有时间改吧。

#include <iostream>
using namespace std;

template<class TYPE>
struct Node
{
 TYPE info;
 Node<TYPE> *next;
 Node(TYPE i,Node<TYPE> *nx)
 {
  this->info=i;
  this->next=nx;
 }
};

template<class TYPE>
class Sqlist
{
 Node<TYPE> *m_head;
 Node<TYPE> *m_tail;
 int length;
public:
 Sqlist():m_head(0),m_tail(0),length(0){}
 Sqlist(const Sqlist<TYPE>& sl);
 Sqlist& operator=(const Sqlist<TYPE> sl);

 void Insert(int index,TYPE elem);
 void Remove(int index);
 int  Find(TYPE elem);
 void RemoveAll();
 void push_back(TYPE elem);
 void push_front(TYPE elem);
 void pop_back();
 void pop_front();
};

template<class TYPE>
Sqlist<TYPE>::Sqlist(const Sqlist<TYPE>& sl)
{
 pos=s1.pos;
 length=s1.length;
 for(Node<TYPE> *pNode=s1.m_head;;pNode=pNode->next)
 {
  push_back(pNode->info);
  if(pNode==s1.m_tail)
   break;
 }
}


template<class TYPE>
Sqlist<TYPE>& Sqlist<TYPE>::operator=(const Sqlist<TYPE> sl)
{
 pos=s1.pos;
 length=s1.length;
 for(Node<TYPE> *pNode=s1.m_head;;pNode=pNode->next)
 {
  push_back(pNode->info);
  if(pNode==s1.m_tail)
   break;
 }
 return *this;
}


template<class TYPE>
void Sqlist<TYPE>::push_back(TYPE elem)
{
 Node<TYPE> *keyNode=new Node<TYPE>(elem,NULL);
 if(m_head==NULL)
  m_head=m_tail=keyNode;
 else
 {
  m_tail->next=keyNode;
  m_tail=keyNode;
 }
 length++;
}


template<class TYPE>
void Sqlist<TYPE>::push_front(TYPE elem)
{
 Node<TYPE> *keyNode=new Node<TYPE>(elem,NULL);
 if(m_head==NULL)
  m_head=m_tail=keyNode;
 else
 {
  keyNode->next=m_head;
  m_head=keyNode;
 }
 length++;
}


template<class TYPE>
void Sqlist<TYPE>::pop_back()
{
 if(m_head==NULL)
  return;
 else if(m_head==m_tail)
 {
  delete m_head;
  m_head=m_tail=NULL;
  return;
 }
 for(Node<TYPE>*temp=m_head;;temp=temp->next)
  if(temp->next==m_tail)
  {
   delete m_tail;
   m_tail=temp;
   break;
  }
 length--;
}

 

template<class TYPE>
void Sqlist<TYPE>::pop_front()
{
 if(m_head==NULL)
  return;
 else if(m_head==m_tail)
 {
  delete m_head;
  m_head=m_tail=NULL;
  return;
 }
 Node<TYPE>*temp=m_head;
 m_head=m_head->next;
 delete temp;
 length--;
}

 

template<class TYPE>
void Sqlist<TYPE>::Insert(int index,TYPE elem)
{
 if(index>length||index<0)
  return;
 if(index==length)
 {
  push_back(elem);
  return;
 }
 if(index==0)
 {
  push_front(elem);
  return;
 }
 Node<TYPE> *keyNode=new Node<TYPE>(elem,NULL);
 Node<TYPE>* old=NULL;

 for(int i=0,Node<TYPE>*temp=m_head;i<length;i++,temp=temp-

开发经验 | 阅读 1548 次
文章评论,共0条
游客请输入验证码
浏览67792次