#ifndef _LIST_H
#define _LIST_H
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 Delete(Type);
void Insert(Type);
void Invert(); // 翻转,
void Concatenate(List<Type>); // 链接,
void Show(); // 测试用的,
private:
ListNode<Type> *first;
};
template<class Type>
ListNode<Type>::ListNode(Type element)
{
data = element; // 参数就是节点里的数据放到data里边,
link = 0;
}
template<class Type>
void List<Type>::Insert(Type k)
{
ListNode<Type> *newnode = new ListNode<Type>(k);
newnode->link = first; // 新的节点作为第一个节点,
first = newnode;
}
template<class Type>
void List<Type>::Delete(Type k)
{
ListNode<Type> *previous = 0; // 前一个,
ListNode<Type> *current;
for(current = first;
current && current->data != k;
previous = current, current = current->link)
{
;// 什么都不做,空循环,找到要被删除的节点,
}
if(current)
{
if(previous) previous->link = current->link;
else first = first->link;
delete current;
}
}
template<class Type>
void List<Type>::Concatenate(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;
}
}
template<class Type>
void List<Type>::Invert()
{
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>::Show()
{
for(ListNode<Type> *current = first; current;current = current->link)
{
std::cout << current->data;
if(current->link) std::cout << " -> ";
}
std::cout << std::endl;
}
#endif _LIST_H
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
List<int> intList;
intList.Insert(31);
intList.Insert(12);
intList.Insert(3);
intList.Insert(6);
intList.Show();
intList.Invert();
intList.Show();
intList.Delete(6);
intList.Show();
intList.Delete(60);
intList.Show();
List<char> charList;
charList.Insert('x');
charList.Insert('i');
charList.Insert('a');
charList.Insert('o');
charList.Invert();
charList.Show();
List<char> charList2;
charList2.Insert('c');
charList2.Insert('u');
charList2.Insert('i');
charList2.Invert();
charList2.Show();
charList.Concatenate(charList2);
charList.Show();
return 0;
}