两种方法逆转一个列表,临时变量和递归
#include <stdio.h>
#include <iostream>
using namespace std;
struct Node
{
int value;
Node* next;
};
Node* buildList(){
Node* head=new Node;
Node* temp_prev=head;
int i=0;
while(i<10){
Node* node=new Node;
node->value=i;
node->next=NULL;
temp_prev->next=node;
temp_prev=node;
i++;
}
return head;
}
Node* reverse(Node* head){
Node* prev=NULL;
Node* next=NULL;
Node* temp=head->next;
while(temp){
next=temp->next;
temp->next=prev;
prev=temp;
temp=next;
}
head->next=prev;
return head;
}
Node* reverseDigui(Node* pNode,Node* head){
if(pNode->next==NULL){
//重新设置HEAD
head->next=pNode;
return pNode;
}
Node* temp=reverseDigui(pNode->next,head);
temp->next=pNode;
//设置原来的第一个节点的NEXT,以免成环
pNode->next=NULL;
return pNode;
}
int main(){
Node* head=buildList();
Node* node=head->next;
while(node){
cout<<node->value<<endl;
node=node->next;
}
//非递归
//reverse(head) ;
//递归
reverseDigui(head->next,head);
node=head->next;
while(node){
cout<<node->value<<endl;
node=node->next;
}
return 0;
}