zoukankan      html  css  js  c++  java
  • leetcode 92. Reverse Linked List II

    题目内容

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

    Example:
    Note: 1 ≤ m ≤ n ≤ length of list.
    
    Example:
    
    Input: 1->2->3->4->5->NULL, m = 2, n = 4
    Output: 1->4->3->2->5->NULL
    
    

    分析过程

    • 题目归类:
      链表,递归方式链表
    • 题目分析:
      本题目的是控制链表的部分反转,我采用的方法是修改了递归链表反转算法
    • 边界分析:
      • 空值分析
      • 循环边界分析
    • 方法分析:
      • 数据结构分析
      • 状态机
      • 状态转移方程
      • 最优解
    • 测试用例构建

    代码实现

    递归

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head == null)
                return null;
            int l = n-m;
            ListNode node = new ListNode(0);
            node.next = head;
            ListNode tmp =node;
            while(m>1){
                node = node.next;
                m--;
            }
            node.next=reverse(node.next,l);
            return tmp.next;
        }
        public ListNode reverse(ListNode head, int i){
            if(i == 0||head==null||head.next==null){
                return head;
            }
            ListNode tmp = reverse(head.next,i-1);
            ListNode y = head.next.next;
            head.next.next = head;
            head.next = y;
            return tmp;
        }
    }
    
    
    

    效率提高

    拓展问题

  • 相关阅读:
    Scala篇:Scala环境及IDEA配置
    大数据篇:Hive
    大数据篇:Flume
    大数据篇:Kafka
    15.百万考生成绩如何排序
    Tomcat 架构原理解析到架构设计借鉴
    服务设计思考:平台化
    Druid:通过 Kafka 加载流数据
    12.分而治之-归并排序
    11.经典O(n²)比较型排序算法
  • 原文地址:https://www.cnblogs.com/clnsx/p/12308439.html
Copyright © 2011-2022 走看看