题解 | #排序奇升偶降链表#

排序奇升偶降链表

https://www.nowcoder.com/practice/3a188e9c06ce4844b031713b82784a2a

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode sortLinkedList (ListNode head) {
        // write code here
        // 解题思路:遍历链表,取出来奇数链表和偶数链表
        // 对偶数链表反转
        // 合并2个链表
        if (head == null) {
            return null;
        }

        ListNode q = new ListNode(0);
        ListNode o = new ListNode(0);
        ListNode curQ = q;
        ListNode curO = o;
        int i = 1;

        while (head != null) {
            if (i % 2 == 0) {
                curO.next = new ListNode(head.val);
                curO = curO.next;
            } else {
                curQ.next = new ListNode(head.val);
                curQ = curQ.next;
            }
            i++;
            head = head.next;
        }

        ListNode reO = resever(o.next);
        curQ = q.next;
        ListNode root = new ListNode(0);
        ListNode cur = root;

        while (reO != null || curQ != null) {
            int valO = (reO == null) ? Integer.MAX_VALUE : reO.val;
            int valQ = (curQ == null) ? Integer.MAX_VALUE : curQ.val;

            if (valO > valQ) {
                cur.next = new ListNode(valQ);
                curQ = curQ.next;
            } else {
                cur.next = new ListNode(valO);
                reO = reO.next;
            }

            cur = cur.next;
        }

        return root.next;
    }

    private ListNode resever(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode pre = null;
        ListNode next;

        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }

        return pre;
    }
}

全部评论

相关推荐

01-14 19:01
吉首大学 Java
黑皮白袜臭脚体育生:加个项目吧,一般需要两个项目一业务一轮子呢,简历统一按使用了什么技术实现了什么功能解决了什么问题或提升了什么性能指标来写
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务