zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    
    }
  • 相关阅读:
    CTF MISC-USB流量分析出题记录
    python-flask-ssti(模版注入漏洞)
    如何写一个Xss Bot
    nginx解析漏洞,配置不当,目录遍历漏洞环境搭建、漏洞复现
    weblogic在linux和window下的安装
    apache-日志-记录post数据
    条件竞争漏洞
    arpspoof+driftnet+ ARP欺骗简单图片抓取
    图片隐写--XOR&OR&and
    qcow2虚拟磁盘映像转化为vmdk
  • 原文地址:https://www.cnblogs.com/null00/p/5102040.html
Copyright © 2011-2022 走看看