ITeye博客

单链表逆序

ping8899 · 2011-12-21 11:24 · java · 单链表逆序 · Markdown

实现一:

#include "stdafx.h" #include using namespace std; template struct MyNode { T id; MyNode * next; MyNode(T _id) { id = _id; next = NULL; } }; template class MyList { MyNode * head; MyNode * current; public: MyList() : head(NULL) {} void add(T value) { MyNode* node = new MyNode(value); if(head == NULL) { head = node; current = head; } else { current->next = node; current = node; } } void showAll() { MyNode *go = head; while(go != NULL) { cout<id<<endl; go = go->next; } } void reverse() { MyNode *preNode = NULL; MyNode *currentNode = head; MyNode *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 *list = new MyList(); list->add(123); list->add(456); list->add(789); list->showAll(); list->reverse(); cout<<"after reverse:"<<endl; list->showAll(); system("pause"); return 0; }

实现二:

#include #include<conio.h> #include using namespace std;

template struct Node{ T value; struct Node* 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(); }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。