• LeetCode


    题目:

    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->NULL, m = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given m, n satisfy the following condition:
    1 ≤ mn ≤ length of list.

    思路:

    以下代码很多,但逻辑很直接,应该还可以简化

    package list;
    
    public class ReverseLinkedListII {
    
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if (m == n) return head;
            ListNode p = new ListNode(0);
            p.next = head;
            ListNode firstPivot = null;
            ListNode firstPivotNext = null;
            ListNode prev = p;
            ListNode node = head;
            int i = 1;
            while (i <= n) {
                if (i > m && i < n) {
                    ListNode tmp = node;
                    node = node.next;
                    tmp.next = prev;
                    prev = tmp;
                } else if (i < m) {
                    node = node.next;
                    prev = prev.next;
                } else if (i == m) {
                    firstPivot = prev;
                    firstPivotNext = node;
                    ListNode tmp = node;
                    node = node.next;
                    tmp.next = null;
                    prev = tmp;
                } else if (i == n) {
                    ListNode tmp = node;
                    node = node.next;
                    tmp.next = prev;
                    firstPivot.next = tmp;
                    firstPivotNext.next = node;
                }
                ++i;            
            }
            return p.next;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ListNode a1 = new ListNode(1);
            ListNode a2 = new ListNode(2);
            ListNode a3 = new ListNode(3);
            ListNode a4 = new ListNode(4);
            ListNode a5 = new ListNode(5);
            a1.next = a2;
            a2.next = a3;
            a3.next = a4;
            a4.next = a5;
            a5.next = null;
            ReverseLinkedListII r = new ReverseLinkedListII();
            ListNode head = r.reverseBetween(a1, 2, 5);
            while (head != null) {
                System.out.println(head.val);
                head = head.next;
            }
        }
    
    }
  • 相关阅读:
    redis(lettuce)
    Dubbo与SSM整合(认证授权)步骤
    maven常用命令
    Dubbo(RPC框架)
    SpringCache
    mybatis(SSM整合)
    java设计模式-命令模式
    java设计模式-原型模式
    java设计模式-职责链模式
    java设计模式-建造者模式
  • 原文地址:https://www.cnblogs.com/null00/p/5102040.html
Copyright © 2020-2023  润新知