zoukankan      html  css  js  c++  java
  • [LeetCode] 148. 排序链表

    用归并排序一个链表。

    /**
     * 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) {
            return sortList(head, null);
        }
    
        public ListNode sortList(ListNode head, ListNode tail) {
            if (head == null) {
                return head;
            }
            if (head.next == tail) {
                head.next = null;
                return head;
            }
            ListNode slow = head, fast = head;
            while (fast != tail) {
                slow = slow.next;
                fast = fast.next;
                if (fast != tail) {
                    fast = fast.next;
                }
            }
            ListNode mid = slow;
            ListNode list1 = sortList(head, mid);
            ListNode list2 = sortList(mid, tail);
            ListNode sorted = merge(list1, list2);
            return sorted;
        }
    
        private ListNode merge(ListNode head1, ListNode head2) {
            ListNode ret = new ListNode(0);
            ListNode tmp = ret;
            while (head1 != null && head2 != null) {
                if (head1.val > head2.val) {
                    tmp.next = head2;
                    head2 = head2.next;
                } else {
                    tmp.next = head1;
                    head1 = head1.next;
                }
                tmp = tmp.next;
            }
            if (head1 != null) tmp.next = head1;
            if (head2 != null) tmp.next = head2;
    
            return ret.next;
        }
    }
    
  • 相关阅读:
    FastDFS
    目前存在的问题
    MongoDB JAVA开发
    [Linux] Hexo 搭建个人博客
    新目标
    1年之后的拿高工资的资本,Java线程
    Oracle在VMware虚拟机安装的配置
    adb命令关闭打开手机wifi开关
    ADB命令横竖屏切换、关闭打开wifi
    使用adb命令提取安卓手机中安装的apk
  • 原文地址:https://www.cnblogs.com/acbingo/p/14856908.html
Copyright © 2011-2022 走看看