#ifndef __LIST_H__
#define __LIST_H__
#include <iostream>
using namespace std;
template <class Type> class List; //声明节点
template <class Type>
class ListNode //节点
{
friend class List<Type>;
private:
Type data;
ListNode *link;
ListNode(Type);
};
template <class Type>
class List{
public:
List() {first=0;}; //初始化构造函数
void Insert(Type); //插入数据
void Delet(Type); //删除数据
void convert(); //反转
void Connect(List<Type>); //连接两个
void show();
private:
ListNode<Type> *first; //指向第一个
};
template <class Type>
ListNode<Type>::ListNode(Type element)//构造函数
{
data=element;
link=0;
}
template<class Type>
void List<Type>::Insert(Type K)
{
ListNode<Type> *node= new ListNode<Type>(K);
node->link=first; //在头插入 ,把first指向第一个的节点赋给node link
first=node; //node指向就是第一个节点
}
template<class Type>
void List<Type>::show() //显示
{
for(ListNode<Type> *current=first;current;current=current->link)
{
cout<<current->data<<' ';
}
cout<<endl;
}
template<class Type>
void List<Type>::Delet(Type element) //删除数据
{
ListNode<Type> *previous=0; //保存前一个数据
ListNode<Type> *current; //保存现今的数据
for(current=first;current&& current->data!=element;previous=current,current=current->link); //依次查找 数据
if(current)
{
if(previous) previous->link=current->link; //如果不是第一个数据 ,前一个节点指向到下一个节点
else first=first->link;
delete current; //删除new的node
}
}
template<class Type>
void List<Type>::convert() //进行数据反转
{
ListNode<Type> *p=first, *q=0; //将第一个和最后一个交换
while(p)
{
ListNode<Type> *r=q;q=p;
p=p->link;
q->link=r;
}
first=q;
}
template<class Type>
void List<Type>::Connect(List<Type> b)
{
if(!first) //如果第一个链表为空,将第二个链表的直接接在第一个的头部
{first=b.first;
return;
}
if(b.first)
{
ListNode<Type> *p;
for(p=first;p->link;p=p->link); //循环到最后一个数据
p->link=b.first; //将最后一个数的下一个接在第一个数的头部
}
}
#endif // __LIST_H__
main
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
List<int> K;
K.Insert(10);
K.Insert(12);
K.Insert(20);
K.show();
K.Delet(20);
K.show();
K.convert();
K.show();
//cout << "Hello world!" << endl;
return 0;
}