zoukankan      html  css  js  c++  java
  • 算法-重排链表

    /**
    https://leetcode-cn.com/problems/reorder-list/submissions/
    * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public void reorderList(ListNode head) { if(head == null || head.next == null || head.next.next == null){ return; } // 通过快慢指针方法找到链表中间节点,如果是偶数节点个数,则是前半部分最后一个节点,使用dummy节点方便处理 ListNode dummy = new ListNode(); dummy.next = head; ListNode fast = dummy; ListNode slow = dummy; while(fast != null && fast.next != null){ fast = fast.next.next; slow = slow.next; } // 链表后半部分反转,头插法 ListNode cur = slow.next.next; ListNode tail = slow.next; while(cur != null){ ListNode midNext = slow.next; slow.next = cur; cur = cur.next; slow.next.next = midNext; } tail.next = null; // 重排 ListNode headPoint = head; while(slow.next != null && slow != headPoint){ ListNode tmpMove = slow.next; slow.next = slow.next.next; ListNode tmpAfterHeadPoint = headPoint.next; headPoint.next = tmpMove; tmpMove.next = tmpAfterHeadPoint; headPoint = headPoint.next.next; } } }

     方法二: 递归

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public void reorderList(ListNode head) {
            if(head == null || head.next == null){
                return;
            }
         // 计算链表长度
            int size = 0;
            ListNode headPoint = head;
            while(headPoint != null){
                headPoint = headPoint.next;
                size ++;
            }
            ListNode tail = reverse(head,size);
    
        }
      // 根据链表长度递归,并在每次递归中返回上层需要处理的尾节点的指针 ListNode reverse(ListNode head,
    int length){ if(length == 1){ ListNode tmp = head.next; head.next = null; return tmp; } if(length == 2){ ListNode tmp = head.next.next; head.next.next = null; return tmp; } ListNode tail = reverse(head.next,length - 2); ListNode tailNext = tail.next; ListNode tmpHeadNext = head.next; head.next = tail; tail.next = tmpHeadNext; return tailNext; } }
  • 相关阅读:
    SkyWalking链路追踪系统-告警篇
    在k8s中解决pod资源的正确识别
    SkyWalking链路追踪系统-接入篇
    Jenkins API+Pipeline深度实践之input的自动化
    SkyWalking链路追踪系统-部署篇
    DevOps建设之基于钉钉OA审批流的自动化上线
    使用kube-prometheus部署k8s监控(最新版)
    基于k8s手动部署rabbitmq集群
    ant desgin vue中table复选框根据状态disabled置灰
    ant design vue 中tree实现单选
  • 原文地址:https://www.cnblogs.com/caiyao/p/13035602.html
Copyright © 2011-2022 走看看