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

    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.

    Summary: First writes down the reverse parts (m to n) , then handles nodes before the m-th node and after the n-th node.

     1 class Solution {
     2 public:
     3     ListNode *reverseBetween(ListNode *head, int m, int n) {
     4         ListNode * current = head;
     5         ListNode * pre_m_node = NULL;
     6         ListNode * new_head = NULL;
     7         int i = 0;
     8         while(current != NULL) {
     9             if(i == m -1)
    10                 break;
    11             pre_m_node = current;
    12             i ++;
    13             current = current -> next;
    14         }
    15         //reverse m to n
    16         ListNode * pre_n_node = current; 
    17         int num_of_reverse_op = 0;
    18         int num_of_nodes_to_reverse = n - m + 1;
    19         while(num_of_reverse_op < num_of_nodes_to_reverse) {
    20             ListNode * pre_head = new_head;
    21             new_head = current;
    22             current = current -> next;
    23             num_of_reverse_op ++;
    24             new_head -> next = pre_head;
    25         }
    26         //connect rest node after the nth node
    27         pre_n_node -> next = current;
    28         
    29         if(pre_m_node != NULL) {
    30             pre_m_node -> next = new_head;
    31             return head;
    32         } else {
    33             return new_head;
    34         }
    35     }
    36 };
  • 相关阅读:
    React之JSX语法
    Visual Studio Code 使用 Typings 实现智能提示功能
    React.js 之hello word
    Linux命令详解-cd
    Linux命令详解-ls
    linux常用命令
    LINUX系统配置相关
    netsh
    Visual Studio
    乘法算术表
  • 原文地址:https://www.cnblogs.com/guyufei/p/3394279.html
Copyright © 2011-2022 走看看