首页 > 编程语言 > 详细

leetcode(剑指offer 24)-反转链表C++实现

时间:2021-07-02 11:44:45      阅读:13      评论:0      收藏:0      [点我收藏+]

剑指 Offer 24. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre=nullptr;
        ListNode* cur=head;
        while(cur)
        {
            ListNode* nextnode=cur->next;
            cur->next=pre;
            pre=cur;
            cur=nextnode;
        }
        return pre;


        // if(head==NULL) return NULL;
        // if(head->next == NULL) return head;
        // ListNode* last = reverseList(head->next);
        // head->next->next = head;
        // head->next = NULL;
        // return last;
    }
};

  

注释掉的是递归写法

 

92. 反转链表 II - 力扣(LeetCode) (leetcode-cn.com)

递归写法,如果left==1,则进入reverseN函数,反转[1,right]的结点。

reverseN函数中,要记录下第right+1个结点,当区间内的反转完成后要让头指针指向那个right+1结点。

left-1,right-1这里就是记录到当前头节点的相对距离,head结点每次往后一个结点,相对距离就要减1,当left==1的时候就变成了reverseN的情况。

/**
 * 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* node=nullptr;
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if(head==nullptr) return nullptr;
        if(left==1)
        {
            return reverseN(head,right);
        }
        head->next=reverseBetween(head->next,left-1,right-1);
        return head;
    }

    ListNode* reverseN(ListNode* head,int n)
    {
        if(n==1)
        {
            node=head->next;
            return head;
        }
        ListNode* last=reverseN(head->next,n-1);
        head->next->next=head;
        head->next=node;
        return last;
    }
};

  

leetcode(剑指offer 24)-反转链表C++实现

原文:https://www.cnblogs.com/Jessicax/p/14961563.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!