递归,迭代,堆栈三种方式实现单链表反转(C++)

#author by changingivan
# 2016.04.12
#include <iostream> #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; }

 

原文链接: https://www.cnblogs.com/changingivan/p/5384069.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    递归,迭代,堆栈三种方式实现单链表反转(C++)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/231807

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午3:11
下一篇 2023年2月13日 下午3:11

相关推荐