实现一:
#include "stdafx.h"
#include <iostream>
using namespace std;
template <typename T>
struct MyNode
{
T id;
MyNode * next;
MyNode(T _id)
{
id = _id;
next = NULL;
}
};
template <typename T>
class MyList
{
MyNode<T> * head;
MyNode<T> * current;
public:
MyList() : head(NULL) {}
void add(T value)
{
MyNode<T>* node = new MyNode<T>(value);
if(head == NULL)
{
head = node;
current = head;
}
else
{
current->next = node;
current = node;
}
}
void showAll()
{
MyNode<T> *go = head;
while(go != NULL)
{
cout<<go->id<<endl;
go = go->next;
}
}
void reverse()
{
MyNode<T> *preNode = NULL;
MyNode<T> *currentNode = head;
MyNode<T> *nextNode = head->next;
while(true)
{
nextNode = currentNode->next;
currentNode->next = preNode;
preNode = currentNode;
currentNode = nextNode;
if(currentNode->next == NULL)
{
head = currentNode;
head->next = preNode;
break;
}
}
}
};
int main(int argc, char * argv[])
{
MyList<int> *list = new MyList<int>();
list->add(123);
list->add(456);
list->add(789);
list->showAll();
list->reverse();
cout<<"after reverse:"<<endl;
list->showAll();
system("pause");
return 0;
}
实现二:
#include<iostream>
#include<conio.h>
#include<list>
using namespace std;
template<class T>
struct Node{
T value;
struct Node<T>* next;
Node(const T& v):value(v),next(NULL){}
~Node(){
delete next;
next=NULL;
cout<<"~Node()"<<endl;
}
};
template<class T,class N>
class Iterator{
public:
Iterator(T v=NULL):t(v){}
T& operator++()const{
t=t->next;
return t;
}
const N& operator*()const{
return t->value;
}
N&operator*(){
return t->value;
}
const T& getT()const{
return t;
}
Iterator& operator=(Iterator& other){
t=other.getT();
return *this;
}
const Iterator& operator=(Iterator& other)const{
t=other.getT();
return *this;
}
private:
mutable T t;
};
template<class T,class N>
bool operator!=(Iterator<T,N> i1,Iterator<T,N> i2){
return i1.getT()!=i2.getT();
}
template<class T>
class NList{
public:
typedef Iterator<Node<T>*,T> iterator;
typedef const Iterator<Node<T>*,T> const_iterator;
NList(const T& value){
head=tail=new Node<T>(value);
}
void addNode(const T& value){
tail->next=new Node<T>(value);
tail=tail->next;
}
iterator begin(){
return iterator(head);
}
iterator end(){
return iterator(tail->next);
}
void reverse(){
if(head==tail)
return ;
Node<T>* end=head,*begin=tail;
Node<T>* p1=head,*p2,*p3;
p2=p1->next;
p1->next=NULL;
while(p2!=tail){
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
p2->next=p1;
head=begin,tail=end;
}
~NList(){
delete head;
head=NULL;
tail=NULL;
cout<<"~NList()"<<endl;
}
private:
Node<T>* head;
Node<T>* tail;
};
int main(){
NList<int> nlist(1);
nlist.addNode(2);
nlist.addNode(3);
NList<int>::const_iterator p=nlist.begin(),end=nlist.end();
for(p=nlist.begin();p!=end;++p)
cout<<*p<<endl;
nlist.reverse();
end=nlist.end();
for(p=nlist.begin();p!=end;++p)
cout<<*p<<endl;
getch();
return 0;
}