题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <bits/types/struct_tm.h>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        // write code here
        ListNode* list_head = head;
        // find right pos
        ListNode* start_node = nullptr;
        ListNode* right_node = head;
        ListNode* cursor_node = head;
        int size = 0;
        // find right_node and claim start_node if pos not equals 1
        for (int i = 1; i <= n; i++, size++) {
            if (cursor_node == nullptr) {
                break;
            }
            if (i == n) {
                right_node = cursor_node;
            }
            if (m > 1 && i == m - 1) {
                start_node = cursor_node;
            }
            cursor_node = cursor_node->next;
        }
        // special condition: m equals 1, construct an empty node as head node
        if (nullptr == start_node && m == 1) {
            start_node = new ListNode(2000);
            start_node->next = head;
        }

        // save temp start_node->next
        ListNode* tmp_node = start_node->next;
        // start_node->next point to right_node
        start_node->next = right_node;
        // then tail insert
        while (tmp_node != right_node) {
            ListNode* tmp_next_node = tmp_node->next;
            tmp_node->next = right_node->next;
            right_node->next = tmp_node;
            tmp_node = tmp_next_node;
        }

        // special condition
        if (m == 1) {
            list_head = start_node->next;
        } else {
            list_head = head;
        }
        return list_head;
    }
};

全部评论

相关推荐

今年读完研的我无房无车无对象,月入还没有过万&nbsp;看到他在朋友圈晒房产证,感叹自己白读了这么多年书
梦想是成为七海千秋:那咋了,双9毕业的现在还没存款呢(因为没念完),高中毕业的去直播带货月入几百万也是完全有可能的,退一万步讲,有些人刚出生父母就给买车买房了,上哪说理去,哪怕是同一个起点也会有截然不同的走向,过好自己的生活就完事了。
点赞 评论 收藏
分享
牛客928043833号:在他心里你已经是他的员工了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务