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 };
  • 相关阅读:
    使用virtualenvwrapper隔离python环境
    Ubuntu创建launcher
    Python单步调试
    Jupyter增加内核
    扩展User增加部门字段
    EasyUI ComboBox默认值
    C#调用dll时的类型转换
    更改VisualStudio默认创建类和接口不加public问题
    IL学习资料
    服务注册中心,Eureka比Zookeeper好在哪里?
  • 原文地址:https://www.cnblogs.com/guyufei/p/3394279.html
Copyright © 2011-2022 走看看