非常簡(jiǎn)單的實(shí)現(xiàn),設(shè)置3個(gè)指針,分別指向當(dāng)前節(jié)點(diǎn)、前一個(gè)節(jié)點(diǎn)、后一個(gè)節(jié)點(diǎn),然后依次處理所有的節(jié)點(diǎn)就OK了。
具體代碼為:
#include <iostream>
using namespace std;
#ifndef null
#define null (void*)0
#endif
typedef struct node
{
struct node* next;
int data;
}node;
node* head=(node*)null;
void reverse(node* root)
{
node *cur,*pre,*next;
pre=(node*)null;
cur=root;
next=cur->next;
while(next)
{
cur->next=pre;
pre=cur;
cur=next;
next=cur->next;
}
head=cur;
cur->next=pre;
}
void insert(node* p)
{
p->next=head;
head=p;
}
void del(node* p)
{
node *cur,*next;
cur=p;
next=p->next;
while(next)
{
delete cur;
cur=next;
next=cur->next;
}
delete cur;
}
void print(node* p)
{
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main(int argc,char** argv)
{
for(int i=0;i<10;i++)
{
node* p=new node;
p->next=(node*)null;
p->data=i;
insert(p);
}
print(head);
cout<<"reverse order:"<<endl;
reverse(head);
print(head);
del(head);
system("pause");
return 0;
}