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->NULL, m = 2 and n = 4,

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

    Note:Given m, n satisfy the following condition: 1 ? m ? n ? length of list.

    解法:需要定位待翻转部分的头与尾,以及翻转部分相邻的两个节点,同时还要考虑m和n之间的关系。

     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         ListNode *left = new ListNode(0);
    15         left->next = head;
    16         if(m < 1){
    17             return head;
    18         }
    19         int len = n-m;
    20         if(len < 1){
    21             return head;
    22         }
    23         for(int i=1; i<m; i++){
    24             left = left->next;
    25         }
    26         ListNode *phead = left->next;
    27         ListNode *pre = left->next;
    28         ListNode *lat = pre->next;
    29         ListNode *tail = lat->next;
    30         while(tail && len-1){
    31             lat->next = pre;
    32             pre = lat;
    33             lat = tail;
    34             tail = lat->next;
    35             len--;
    36         }
    37         lat->next = pre;
    38         phead->next = tail;
    39         left->next = lat;
    40         if(m == 1){
    41             return left->next;    
    42         }else{
    43             return head;
    44         }
    45     }
    46 };

    Run Status: Accepted!
    Program Runtime: 20 milli secs

    Progress: 44/44 test cases passed.
  • 相关阅读:
    C 数组初始化
    Linux函数之snprintf()[一]
    出现一下错误
    IOS通过post方式发送图片续
    IOS通过post方式发送图片
    TCP和UDP的区别趣解
    [转]Release mode debugging with VC++
    [转]Math For Programmers
    OS:kernel and shell
    Reminder: 8020 rule
  • 原文地址:https://www.cnblogs.com/infinityu/p/3074295.html
Copyright © 2011-2022 走看看