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

#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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值