zoukankan      html  css  js  c++  java
  • Leetcode 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=1时会变动头节点,所以加入一个dummy头节点
     
    1. 找到原链表中第m-1个节点start:反转后的部分将接回改节点后。
    从dummy开始移动m-1步
     
    D->1->2->3->4->5->NULL
           |
          st
     
    2. 将从p = start->next开始,长度为L = n-m+1的部分链表反转。
                __________
                |                  |
                |                 V
    D->1->2<-3<-4    5->NULL             
           |     |           | 
          st    p          h0         
     
    3. 最后接回
     
                __________
                |                  |
                |                 V
    D->1   2<-3<-4    5->NULL             
           |________|                

    Java code:
    20160601
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            //iterative
            //base case
            if (head == null || head.next == null || m < 1 || m >= n) {
                return head;
            }
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode pre = dummy;
            ListNode cur = head;
            //move m-1 to the node before reverse start 
            int count = 1;
            while (count < m) {
                pre = cur;
                cur = cur.next;
                count++;
            }
            ListNode beforeReverse = pre;
            ListNode startReverse = cur;
            
            while (count <= n) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
                count++;
            }
            beforeReverse.next = pre;
            startReverse.next = cur;
            return dummy.next;
        }
    }

    Reference:

    1. http://bangbingsyb.blogspot.com/2014/11/leetcode-reverse-linked-list-ii.html
     
  • 相关阅读:
    struts2.0利用注解上传和下载图片
    hibernate @ManyToOne
    Cookie会话管理
    ServletContext
    Servlet 1
    ArrayList
    BigInteger类和BigDecimal类
    Math类
    System类
    基本类型包装类
  • 原文地址:https://www.cnblogs.com/anne-vista/p/5551671.html
Copyright © 2011-2022 走看看