92、Reverse Linked List II [Leetcode]

Reverse Linked List II

题目描述

这里写图片描述

在链表原位置上,翻转位置m到n上的结点,指遍历链表一次

分析

如何找到第m个元素和第n个元素
如何处理前面和后面
1.保存前面部分最后一个元素
2. 保存后面部分第一个元素
3. 特殊情况都有哪些:是否需要修改头指针

C代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
    if(head == NULL){
        return NULL;
    }

    struct ListNode* mPre = NULL; //用来保存第m-1个结点地址
    struct ListNode* current = head;
    for(int i=1; i<m; i++){     //退出循环时候,current指向的第m个结点
        mPre = current;
        current = current->next;
    }

    struct ListNode* star = NULL;
    struct ListNode* end = current; 
    struct ListNode* tmp = NULL;
    for(int i=m; i<=n; i++){    //退出循环时候,current指向第n+1个结点
        tmp = current->next;
        current->next = star;
        star = current;
        current = tmp;
    }
    end->next = current;  //将n+1个结点连接到翻转后的链表的末端
    if(mPre == NULL){   //判断是否需要修改头指针
        head = star;
    }else{
        mPre->next = star;
    }
    return head;
}

C++代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(head == NULL)
            return NULL;

        ListNode* mPre = NULL;
        ListNode* now = head;
        for(int i=1; i<m; i++){  //退出循环时候,now指向第m个结点
            mPre = now;
            now = now->next;
        }

        ListNode* tmp = NULL;
        ListNode* star = NULL;
        ListNode* end = now;
        for(int i=m; i<=n; i++){
            tmp = now->next;
            now->next = star;
            star = now;
            now= tmp;
        }
        end->next = now;
        if(mPre == NULL){
            head = star;
        }else{
            mPre->next = star;
        }

        return head;
    }
};

ps:不要每次都还没搞清楚思路就着急着想写代码!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值