链表的基本操作(C++)类的写法、(模板)

#if 1
#include <iostream> 
using namespace std;
template<class Type>
class Link
{
public:
 Link();
 void Insert(Type&);//插入
 void Delete(Type );//删除
 void Reverse();//倒置
 void Print();//输出
 ~Link();//结点的释放
 struct Node
 {
  Node *next;
  Type* p;
 };
 Node *head;
};
template<class Type>
Link<Type>::Link()
{
 head = NULL;
}
template<class Type>
void Link<Type>::Reverse()
{
 Node * current = head ;
 Node * next = NULL ;
 Node * result = NULL ;
 while( current != NULL )
 {
  next = current->next ;
  current->next = result ;
  result = current ;
  current = next ;
 }
 head = result ;
}
template<class Type>
void Link<Type>::Insert(Type& t)
{
 Node* temp = new Node;
 temp->p = &t;
 temp->next = head;
 head = temp;
}
template<class Type>
void Link<Type>::Delete(Type t )
{
 Node * current = head ;
 while( current != NULL )
 {
  if( current->next != NULL &&* (current->next->p) == t )
  {
   Node * tmp = current->next;
   current->next = current->next->next ;
   delete tmp;
   return ;
  }
  current = current->next ;
 }
}
template<class Type>
void Link<Type>::Print()
{
 for (Node *pp = head; pp; pp = pp->next)
 {
  cout << *(pp->p) << " ";
 }
 cout << endl;
}
template<class Type>
Link<Type>::~Link()
{
 Node* pp;
 while (pp = head)
 {
  head = head->next;
  delete pp->p;
  delete pp;
 }
}
int main()
{
 Link<double> DoubleLink;
 for (int i = 1; i < 7; i++)
 {
  DoubleLink.Insert( * new double(i + 0.1) );
 }
 DoubleLink.Delete( double(2.1) );
 DoubleLink.Reverse();
 DoubleLink.Print();
 return 0;
}
#endif

猜你喜欢

转载自blog.csdn.net/qq_40990854/article/details/80531691
今日推荐