zoukankan      html  css  js  c++  java
  • [LeetCode] Reverse Linked List II

    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.

    此题在上题的基础上加了位置要求,只翻转指定区域的链表。由于链表头节点不确定,使用dummy节点。。

    1. 由于只翻转指定区域,分析受影响的区域为第m-1个和第n+1个节点
    2. 找到第m个节点,使用for循环n-m次,使用经典反转算法中的链表翻转方法
    3. 处理第m-1个和第n+1个节点
    4. 返回dummy->next
    /**
     * 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 == nullptr || m > n) 
                return head;
            ListNode* dummy = new ListNode(0);
            dummy->next = head;
            ListNode* node = dummy;
            for (int i = 1; i != m; i++) {
                if (node == nullptr)
                    return node;
                else
                    node = node->next;
            }  
            ListNode* premNode = node;
            ListNode* mNode = node->next;
            ListNode* nNode = mNode;
            ListNode* postnNode = nNode->next;
            for (int i = m; i != n; i++) {
                ListNode* tmp = postnNode->next;
                postnNode->next = nNode;
                nNode = postnNode;
                postnNode = tmp;
            }
            premNode->next = nNode;
            mNode->next = postnNode;
            
            return dummy->next;
        }
    };
    // 6 ms
  • 相关阅读:
    数字音频接口
    xargs命令详解,xargs与管道的区别
    RmNet,CDC-ECM ,NDIS,RNDIS区别
    Python并发编程之多进程(理论)
    网络编程
    type和object
    《流畅的python》读书笔记,第一章:python数据模型
    用 做出进度条
    如何使用特殊方法
    ValueError: too many values to unpack (expected 2)
  • 原文地址:https://www.cnblogs.com/immjc/p/7779011.html
Copyright © 2011-2022 走看看