排序奇升偶降链表-链表拆分反转归并-字节跳动高频题

Posted hequnwang10

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了排序奇升偶降链表-链表拆分反转归并-字节跳动高频题相关的知识,希望对你有一定的参考价值。

一、题目描述

给定一个奇数位升序,偶数位降序的链表,将其重新排序。

示例 1:
输入: 1->8->3->6->5->4->7->2->NULL
输出: 1->2->3->4->5->6->7->8->NULL

二、解题

链表拆分+反转+合并

首先将链表按照奇偶分割,然后将偶数链表翻转,然后在将两个链表合并。链表操作的组合。

class Solution 
    public ListNode sortList(ListNode head)
        // 首先拆分奇偶链表
        ListNode dumyOdd = new ListNode(-1);
        ListNode odd = dumyOdd;

        ListNode dumyEven = new ListNode(-1);
        ListNode even = dumyEven;

        ListNode now = head;
        while(now != null)
            if((now.val & 1) == 1)
                odd.next = now;
                odd = odd.next;
            else
                even.next = now;
                even = even.next;
            
            now = now.next;
        
        odd.next = null;// 将尾节点置为null
        even.next = null;// 将尾节点置为null

        // 接着翻转偶数链表
        even = reverseList(dumyEven.next);
        odd = dumyOdd.next;

        // 最后合并奇偶链表
        return mergeList(odd, even);
    
    private ListNode reverseList(ListNode head)
        ListNode pre = null, now = head;
        while(now != null)
            ListNode temp = now.next;
            now.next = pre;
            pre = now;
            now = temp;
        
        return pre;
    
    // private ListNode reverseList(ListNode head)
    //     if(head == null)
    //         return head;
    //     
    //     ListNode cur = reverseList(head.next);
    //     head.next.next = head;
    //     head.next = null;
    //     return cur;
    // 
    private ListNode mergeList(ListNode odd, ListNode even)
        ListNode dumyList = new ListNode(-1);
        ListNode now = dumyList;
        while(odd != null || even != null)
            if(odd == null)
                now.next = even;
                even = even.next;
            else if(even == null)
                now.next = odd;
                odd = odd.next;
            else
                if(even.val <= odd.val)
                    now.next = even;
                    even = even.next;
                else
                    now.next = odd;
                    odd = odd.next;
                
            
            now = now.next;
        
        return dumyList.next;
    

以上是关于排序奇升偶降链表-链表拆分反转归并-字节跳动高频题的主要内容,如果未能解决你的问题,请参考以下文章

[算法] 排序奇升偶降链表

C++ 排序奇升偶降链表

143. 重排链表-链表拆分+反转+合并-字节跳动高频题

92. 反转链表 II-字节跳动高频题

字节跳动高频算法题TOP100

字节跳动高频算法题TOP100