1、用类模板实现一个链表
#include <iostream>using namespace std;template <class T>
class mylist{
public:// 链表节点struct Link{T val;Link* next;};mylist():head(NULL),tail(NULL){}
// 增 :insert(T val) 在链表中创建新节点,节点上保存的数据为 valmylist& operator<<(T val);
// 删:remove(T val) 移除链表中数据为 val 的节点void remove(T val);
// 改: operator[](int index) 将第index的节点修改T& operator[](int index);
// 排序:sortvoid sort();
// 遍历:show 输出链表中所有节点上 valvoid show();
private:Link* head; // 记录链表的头节点的指针Link* tail; // 记录链表的尾节点的指针
};//****************************************
template<typename T>
void mylist<T>::remove(T val) {Link* current = head;Link* previous = NULL;while (current != NULL) {if (current->val == val) {if (previous == NULL) { // 删除头节点head = current->next;} else {previous->next = current->next;}if (current == tail) { // 删除尾节点tail = previous;}delete current;return;}previous = current;current = current->next;}
}template<typename T>
T& mylist<T>::operator[](int index) {Link* current = head;int count = 1;while (current != NULL) {if (count == index) {return current->val;}current = current->next;count++;}
}template<typename T>
void mylist<T>::sort() {if (head == NULL) return;bool flag;do {flag = false;Link* current = head;while (current->next != NULL){if (current->val > current->next->val){T t;t=current->next->val;current->next->val=current->val;current->val=t;flag = true;}current = current->next;}} while (flag);
}//**************************************************
template<typename T>
mylist<T>& mylist<T>::operator<<(T val)
{Link *newnode=new Link{val,NULL};if(head==NULL){head=tail=newnode;}else{tail->next=newnode;tail=newnode;}return *this;}
template <typename T>
void mylist<T>::show()
{Link *h1=head;while(h1!=NULL){cout<<h1->val<<" ";h1=h1->next;}cout<<endl;delete h1;
}
int main()
{mylist<int> s1;s1<<1<<2<<3<<9<<10;s1.show();s1[3]=999;s1.show();s1.sort();s1.show();return 0;
}