zoukankan      html  css  js  c++  java
  • Reverse Linked List II -- 翻转部分链表

    Reverse a linked list from position m to n. Do it in-place and in one-pass.

    For example:
    Given1->2->3->4->5->NULL, m = 2 and n = 4,

    return1->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(m==n) return head;
    13         ListNode d(-1);
    14         ListNode *root=&d;
    15         root->next=head;
    16         ListNode *pre=root;
    17         for(int i=1;i<m;i++){
    18             pre=pre->next;
    19         }
    20         ListNode *head1=pre;
    21         pre=pre->next;
    22         ListNode *cur=pre->next;
    23         for(int i=m;i<n;i++){
    24             pre->next=cur->next;
    25             cur->next=head1->next;
    26             head1->next=cur;
    27             cur=pre->next;
    28         }
    29         return root->next;
    30     }
    31 };

    这道题是比较常见的链表反转操作,不过不是反转整个链表,而是从m到n的一部分。分为两个步骤,第一步是找到m结点所在位置,第二步就是进行反转直到n结点。反转的方法就是每读到一个结点,把它插入到m结点前面位置,然后m结点接到读到结点的下一个。总共只需要一次扫描,所以时间是O(n),只需要几个辅助指针,空间是O(1)。代码如下: 

  • 相关阅读:
    JVM的生命周期、体系结构、内存管理和垃圾回收机制
    JVM的ClassLoader过程分析
    MySQL Cluster配置概述
    tomcat下bin文件夹下shell文件分析
    Eclipse环境下使用Maven注意事项
    mysql服务器的字符集
    判断文件中是否存在中文字符
    Tomcat/JSP中文编码配置
    Java内存泄露的原因
    Python 开发轻量级爬虫08
  • 原文地址:https://www.cnblogs.com/zl1991/p/7058399.html
Copyright © 2011-2022 走看看