思路:1、反转后头结点变化;2、注意链表可能断裂的情形
#include <iostream> using namespace std; struct Node { int data; Node* next; }; class List{ private: int N; Node* first; public: int size() { return N; } bool isEmpty() { first==NULL; } void insert(int val){ Node* oldfirst=first; first=new Node(); first->data=val; first->next=oldfirst; N++; } void print(){ Node* p=first; while(p){ cout<<p->data<<" "; p=p->next; } cout<<endl; } void reverse(){ if( first==NULL || first->next==NULL ) return; Node* p=first; Node* pPrev=NULL; while(p!=NULL){ Node* pNext=p->next; if(pNext==NULL){ first=p; } p->next=pPrev; pPrev=p; p=pNext; } } }; int main(){ List* l=new List(); for(int i=0;i<10;i++){ l->insert(i); } l->print(); l->reverse(); l->print(); return 0; }
原文地址:http://blog.csdn.net/dutsoft/article/details/26738919