首页 > Java > java教程 > 正文

对给定的 LinkedList 进行排序

王林
发布: 2024-07-23 12:43:43
原创
435 人浏览过

Sort the given LinkedList

问题

注意:sort()方法可用于合并到排序链表

/**
 * 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 ListNode sortList(ListNode head) {
        // using merge sort on the given list
        return merge(head);
    }

    public ListNode merge(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode middleNode = findMiddleNode(head);
        ListNode next = middleNode.next;
        middleNode.next = null;

        ListNode left = merge(head);
        ListNode right = merge(next);
        ListNode sortedNode = sort(left, right);
        return sortedNode;
    }

    public ListNode sort(ListNode l, ListNode r) {
        // base case
        if (l == null)
            return r;
        else if (r == null)
            return l;
        ListNode result = null;

        if (l.val < r.val) {
            result = l;
            result.next = sort(l.next, r);
        } else {
            result = r;
            result.next = sort(l, r.next);

        }
        return result;
    }

    public ListNode findMiddleNode(ListNode head) {
        if (head == null)
            return head;
        ListNode slow = head;
        ListNode faster = head;
        // 1>2>3>null
        // 1>2>null
        // null
        while (faster.next != null && faster.next.next != null) {
            slow = slow.next;
            faster = faster.next.next;
        }
        return slow;
    }
}
登录后复制

以上是对给定的 LinkedList 进行排序的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!