代碼: #include <iostream>
#include <vector>
#include <iterator>
#include <cassert>
#include<algorithm>//copy using namespace std;
const int n=2;
struct node
{
int i;
node *next;
};
node *Reverse(node *head)
{
//判斷鏈表是否爲空
assert(head != NULL && " function Reverse : list is null!");
node *temp=head->next;
//鏈表只有一個元素狀況
if(temp == NULL ) return head;
//鏈表翻轉前head-->temp-->tail,翻轉後tail-->temp-->head
head->next=NULL;
node *tail=temp->next;
while(tail != NULL)
{
temp->next=head;
head=temp;
temp=tail;
tail=tail->next;
}
temp->next=head;
//返回翻轉後的鏈表頭指針
return temp;
}
void Print(node *head)
{
while(head != NULL)
{
cout<<head->i<<" ";
head=head->next;
}
cout<<endl;
}
int main()
{
node *head=NULL,*tail=NULL,*temp=NULL;
head= new node;
head->i=1;head->next=NULL;
tail=head;
for(int i=2;i<=n;++i)
{
temp =new node;
temp->i=i;temp->next=NULL;
tail->next=temp;
tail=temp;
}
Print(head);
cout<<"------------"<<endl;
head=Reverse(head);
Print(head);node
return 0;
}ios