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.

     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         if (head == NULL) return NULL;
    13         
    14         ListNode** pre = &head;
    15         
    16         for (int i = 0; i < m - 1; i++)
    17             pre = &((*pre)->next);
    18         
    19         n -= m;
    20         ListNode* start = *pre;
    21         while (n--) {
    22             ListNode* p = start->next;
    23             start->next = p->next;
    24             p->next = *pre;
    25             (*pre) = p;
    26         }
    27         
    28         return head;
    29     }
    30 };
  • 相关阅读:
    c#剪切板操作
    eclipse mvn build error tips
    Redis Tips
    IntilliJ Idea 使用中的问题与解决方案
    mongo
    python
    SQL Relative
    sybase update
    run current vim file
    git
  • 原文地址:https://www.cnblogs.com/vincently/p/4056291.html
Copyright © 2011-2022 走看看