非常簡單的實現,設置3個指針,分別指向當前節點、前一個節點、后一個節點,然后依次處理所有的節點就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;
}