zoukankan      html  css  js  c++  java
  • 92. 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.

    含义:翻转列表中给定的两个节点间的所有节点

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

     1         if(head == null)return null;
     2         ListNode dummy = new ListNode(0);
     3         dummy.next = head;
     4         ListNode preNode = dummy;
     5         int i=1;
     6         while(preNode.next!=null && i<m)
     7         {
     8             preNode = preNode.next;
     9             i++;
    10         }
    11         if(i<m) return head;
    12         ListNode mNode = preNode.next;
    13         ListNode cur = mNode.next;
    14         while(cur!=null && i<n)
    15         {
    16             ListNode next = cur.next;
    17             cur.next = preNode.next;
    18             preNode.next = cur;
    19             mNode.next = next;
    20             cur = next;
    21             i++;
    22         }
    23         return dummy.next;

    类似题目:206. Reverse Linked List

  • 相关阅读:
    HttpClient后台post 请求webapi
    [SQL Server] 复制数据库任务
    C# js 在页面能执行,放在单独js文件不能执行
    Flink 中的kafka何时commit?
    jar依赖
    AI重要算法
    NonWindowJoin
    Rocket MQ 源码解析
    linear algebra
    Theories of Deep Learning
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7729183.html
Copyright © 2011-2022 走看看