• [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.

    画图会比较容易理解

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *reverseBetween(ListNode *head, int m, int n) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (head == NULL)
    15             return NULL;
    16             
    17         ListNode *q = NULL;
    18         ListNode *p = head;
    19         for(int i = 0; i < m - 1; i++)
    20         {
    21             q = p;
    22             p = p->next;
    23         }
    24         
    25         ListNode *end = p;
    26         ListNode *pPre = p;
    27         p = p->next;
    28         for(int i = m + 1; i <= n; i++)
    29         {
    30             ListNode *pNext = p->next;
    31             
    32             p->next = pPre;
    33             pPre = p;
    34             p = pNext;
    35         }
    36         
    37         end->next = p;
    38         if (q)
    39             q->next = pPre;
    40         else
    41             head = pPre;
    42         
    43         return head;
    44     }
    45 };
  • 相关阅读:
    TreeSet和TreeMap中“相等”元素可能并不相等
    求众数——摩尔投票
    5802. 统计好数字的数目
    快速幂
    LCP 07.传递消息
    332. 重新安排行程(欧拉回路问题)
    126. 单词接龙 II
    879. 盈利计划
    287. 寻找重复数
    239. 滑动窗口最大值
  • 原文地址:https://www.cnblogs.com/chkkch/p/2776273.html
Copyright © 2020-2023  润新知