翻转链表的几种常用方法

1.使用栈结构--因为栈是先进后出的,所以可以将链表的每个结点入栈,然后头节点设置为栈的栈顶元素,然后在以此出栈

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode() : val(0), next(nullptr) {}

 *     ListNode(int x) : val(x), next(nullptr) {}

 *     ListNode(int x, ListNode *next) : val(x), next(next) {}

 * };

 */

class Solution {

public:

    ListNode* reverseList(ListNode* head) {

        if(head==NULL||head->next==NULL){

            return head;

        }

        stack<ListNode*>stk;

        while(head!=NULL){

            stk.push(head);

            head=head->next;

        }

        head=stk.top();

        stk.pop();

        ListNode *result=head;

        while(!stk.empty()){

            head->next=stk.top();

            stk.pop();

            head=head->next;

        }

        head->next=NULL;//因为链表最后结点一定是NULL;

        return result;

    }

};

 2.双链表求解

class Solution {

public:

    ListNode* reverseList(ListNode* head) {

        ListNode *rear=NULL;

        while(head!=NULL){

            ListNode *front=head->next;

            head->next=rear;

            rear=head;

            head=front;

        }

        return rear;

    }

};

3.递归解决 

class Solution {

public:

    ListNode* reverseList(ListNode* head) {

        if(head==NULL||head->next==NULL){

            return head;

        }

        ListNode *result=reverseList(head->next);//result就是最终的头节点

        head->next->next=head;

        head->next=NULL;

        return result;

    }

};

 

以上递归方法 回溯(出栈)时较慢,因为我们是在函数回溯时才进行的修改指针方向.尾递归正好解决这种问题.

4.尾递归

class Solution {

public:

    ListNode *func(ListNode *head,ListNode *newhead){

        if(head==NULL){

            return newhead;

        }

        ListNode *next=head->next;

        head->next=newhead;

        return func(next,head);

    }

    ListNode* reverseList(ListNode* head) {

        return func(head,NULL);

    }

};

 

这种方法就是每次递归时就直接更改了指针的方向,而并非是回溯时才更改,而出栈的效率要比上一个递归要好.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ξ( ✿>◡❛)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值