赞
踩
#include <stack> using namespace std; struct Node { int val; Node *next; }; Node * creat_link() { Node *head=NULL; Node *current=NULL; Node *tmp=NULL; int val=0; int num_node=10; for(int i=0;i<num_node;i++) { val=i+1; if(i==0) { current=(Node*)new(Node); current->val=val; current->next=NULL; head=current; } else { tmp=(Node*)new(Node); tmp->val=val; tmp->next=NULL; current->next=tmp; current=current->next; } } return head; } void show_display_link(Node * head) { Node * current=head; while(current!=NULL) { cout<<current->val<<endl; current=current->next; } cout<<"finish!"<<endl; } Node * reverse_iteration_version(Node * head) { Node * current=NULL; Node * next_node=NULL; Node * pre=NULL; current=head; pre=head; next_node=current->next; current->next=NULL; while(next_node!=NULL) { pre=current; current=next_node; next_node=next_node->next; current->next=pre; } head=current; return head; } Node * reverse_stack_version(Node * head) { stack <Node * > stack_for_link; Node * current,* tmp,*new_head; current=head; while(current!=NULL) { stack_for_link.push(current); current=current->next; } current=stack_for_link.top(); stack_for_link.pop(); new_head=current; while(!stack_for_link.empty()) { tmp=stack_for_link.top(); stack_for_link.pop(); cout<<tmp->val<<endl; current->next=tmp; current=tmp; } tmp->next=NULL; return new_head; } Node * reverse_recursion_version(Node * head) { if(head->next==NULL) { return head; } Node *tmp,*new_head; tmp=head->next; new_head=reverse_recursion_version(tmp); tmp->next=head; head->next=NULL; return new_head; } int main() { Node * head=NULL; cout << "this is normal order" << endl; head=creat_link(); show_display_link(head); cout <<"this is reverse order"<<endl; //head=reverse_iteration_version(head); //head=reverse_iteration_version(head); head=reverse_recursion_version(head); show_display_link(head); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。