• 【Reverse Linked List II】cpp


    题目

    Reverse a linked list from position m to n. Do it in-place and in one-pass.

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    代码

    /**
     * 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) {
            // virtual begin ListNode
            ListNode dummy(-1);
            dummy.next = head;
            // move to the m-1 ListNode
            ListNode *p = &dummy;
            for (int i = 0; i < m-1; ++i) p = p->next;
            ListNode *prev = p;
            ListNode *curr = p->next;
            for (int i = 0; i < n-m; ++i){
                ListNode *tmp = curr->next;
                curr->next = tmp->next;
                ListNode *tmp2 = prev->next;
                prev->next = tmp;
                tmp->next = tmp2;
            }
            return dummy.next;
        }
    };

    Tips:

    这道题的思路沿用我的这一篇日志:http://www.cnblogs.com/xbf9xbf/p/4212159.html

    需要考虑几种case:

    m=1的情况

    n=end的情况

    再submit两次,就OK了。

    ==================================================

    第二次过这道题,大体思路一下子没有完全想起来。想了一下之后,回忆起来了翻转列表类似抽书本的例子。就顺着思路把代码写出来了,一次AC。

    /**
     * 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) {
                ListNode* dummpy = new ListNode(0);
                dummpy->next = head;
                // find start position
                ListNode* start = dummpy;
                for ( int i=0; i<m-1; i++ ) start = start->next;
                // reverse list between start and end
                ListNode* curr = start->next;
                for ( int i=0; i<(n-m); ++i )
                {
                    ListNode* tmp = curr->next;
                    curr->next = tmp->next;
                    tmp->next = start->next;
                    start->next = tmp;
                }
                return dummpy->next;
        }
    };
  • 相关阅读:
    HDU-2262 Where is the canteen 概率DP,高斯消元
    HDU-4418 Time travel 概率DP,高斯消元
    无人驾驶相关数据集
    C++——编译器运行过程
    C++——Struct 和 Union区别
    常用linux指令
    无人驾驶——定位
    Ubuntu 没有 无线网 RTL8821ce 8111 8186
    无人驾驶之传感器融合算法
    LIN通讯
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4464896.html
Copyright © 2020-2023  润新知