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 }
  • 相关阅读:
    objectForKey与valueForKey在NSDictionary中的差异 转发
    客户需求
    Linked to SAP CRM
    测试
    同学们,没事就练习打字吧
    WebCast下载利器iReaper新版发布
    转载一篇帖子《我对软件应聘学生的建议》
    建议ASP.NET Web开发新手学习的几个基础框架
    一般CSS元素及文件命名方法
    Thinkpad T60入手,爱机S41出售
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4918863.html
Copyright © 2011-2022 走看看