链表的基本操作(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值