zoukankan      html  css  js  c++  java
  • Reverse Linked List II 解答

    Question

    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.

    Solution

    Four pointers:

    Dummy node, pre, start, then, tmp

    First, we find the position to start reversal.

    Key point here is to use Dummy node, and pre points the (m - 1) position.

    Then, we use three pointers, start, then, tmp to implement reversal. Just the same way as Reverse Linked List.

    Several points to note here:

    1. Move (m - 1) steps to get pre position

    2. Move (n - m) steps to implement reversal

    3. Link reversed sub-list with original unreversed sub-lists.

    In-place and in one-pass.

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode reverseBetween(ListNode head, int m, int n) {
    11         if (m == n || head == null)
    12             return head;
    13         ListNode dummy = new ListNode(0);
    14         dummy.next = head;
    15         ListNode pre = dummy, start = dummy, then = dummy, tmp = dummy;
    16         // Move pre to (m - 1) position
    17         for (int i = 0; i < (m - 1); i++) {
    18             pre = pre.next;
    19         }
    20         // Start = m
    21         start = pre.next;
    22         then = start.next;
    23         start.next = null;
    24         // Move (n - m) steps for reverse
    25         for (int i = 0; i < (n - m); i++) {
    26             tmp = then.next;
    27             then.next = start;
    28             start = then;
    29             then = tmp;
    30         }
    31         pre.next.next = then;
    32         pre.next = start;
    33         return dummy.next;        
    34     }
    35 }
  • 相关阅读:
    C加加学习之路 1——开始
    哈夫曼树C++实现详解
    Linux常用命令
    Accp第二章:基础知识
    第一章Accp 8.0
    泛型集合
    深入C#数据类型
    初始wondows系统
    深入.NET框架
    二至十五章总结
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4918863.html
Copyright © 2011-2022 走看看