zoukankan      html  css  js  c++  java
  • Reverse Linked List II leetcode

    本题与之前单链表逆置不同的是,加入了范围判断。

    依然沿用之前单链表逆置的方法,只需要再做好起始节点和末尾节点的判断

    说起来容易,做起来复杂,特别是单链表,很容易把人搞晕,所以,在编程之前最后画图理清思路。

    这次在头结点的处理上,不同于以往设置临时头结点的方法,使用了二级指针,这种方法写出来的代码可能比较少,但是不容易理解,对于追求效率的同学未尝不可一试

    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (head == nullptr || head->next == nullptr)
            return head;
        int count = n - (m--) - 1;
        ListNode **pos = &head;
        while (m-- && (*pos)->next != nullptr)
            pos = &((*pos)->next);
        if ((*pos)->next == nullptr)
            return head;
        ListNode *currPos = (*pos)->next;
        ListNode *nextPos = (*pos)->next->next;
        ListNode *prevPos = (*pos);
        while (count-- > 0 && nextPos != nullptr)
        {
            // 改变currPos->next
            currPos->next = prevPos;
    
            // 依次更新prev、curr、next(向后移动)
            prevPos = currPos;
            currPos = nextPos;
            nextPos = nextPos->next;
        }
        if (count == -1) {
            currPos->next = prevPos; // 注意最后一步
            ListNode *temp = *pos;
            *pos = currPos;
            temp->next = nextPos;
        }
        return head;
    }
  • 相关阅读:
    石头的用途
    [转] Analysis: Khronos and OpenGL ARB merge
    ★○值得你我珍藏一世的80句话○★
    PasswordStrength 控件
    NumericUpDownExtender 控件
    ReorderList控件
    Nobot控件拒绝机器人行为
    PopupControlExtender控件
    PagingBulletedList 控件学习
    MutuallyExlcusiveCheckBox控件
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5073860.html
Copyright © 2011-2022 走看看