zoukankan      html  css  js  c++  java
  • 链表--重排链表(leetcode 143

    题解

    这个题是2019年408原题,就是我考研那年的题目,想想一年过去了,还是有点感慨的,希望明年这个时候的自己比现在更厉害吧

    三个步骤:

    (1)找到中间结点

    (2)反转右半部分,记得将左半部分最后一个的next指针指向null(不要留野指针

    (3)根据题目要求左边取一个,右边取一个

    代码:

    public class Solution143 {
        public ListNode reverse(ListNode head){
            ListNode temp = head;
            ListNode temp1 = null;
            ListNode temp2;
            while (temp != null) {
                temp2 = temp.next;
                temp.next = temp1;
                temp1 = temp;
                temp = temp2;
            }
    
            return temp1;
        }
    
    
        public void reorderList(ListNode head) {
            if (head == null || head.next == null || head.next.next == null){
                return;
            }
    
            ListNode fast = head;
            ListNode slow = head;
            while (fast.next != null && fast.next.next != null){
                fast = fast.next.next;
                slow = slow.next;
            }
    
            ListNode right = slow.next;
            slow.next = null;
    
            ListNode rightReverse = reverse(right);
    
            ListNode dummy = new ListNode(-1);
            ListNode temp = dummy;
            ListNode leftTemp = head;
            ListNode rightTemp = rightReverse;
            while (leftTemp != null && rightTemp != null){
                temp.next = leftTemp;
                leftTemp = leftTemp.next;
                temp = temp.next;
                temp.next = rightTemp;
                rightTemp = rightTemp.next;
                temp = temp.next;
            }
            temp.next = leftTemp;
    
        }
    }
    
    
  • 相关阅读:
    Fibonacci Again
    N的10000的阶乘
    HDU2141(二分搜索)
    POJ2366(HASH法)
    10106 Product
    UVA 401 Palindromes
    UVA424 Integer Inquiry
    POJ2503(二分搜索)
    mysql重置root密码
    tidb安装haproxy负载均衡
  • 原文地址:https://www.cnblogs.com/swifthao/p/13199907.html
Copyright © 2011-2022 走看看