Files
leetcode/148.sort-list.java
2025-10-27 16:22:33 +08:00

64 lines
1.6 KiB
Java

/*
* @lc app=leetcode id=148 lang=java
*
* [148] Sort List
*/
// @lc code=start
/**
* 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) {
if(head == null || head.next == null) {
return head;
}
ListNode slow = head, fast = head, prev = null;
while(fast != null && fast.next != null) {
fast = fast.next.next;
prev = slow;
slow = slow.next;
}
prev.next = null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
return merge(l1, l2);
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0), tail = dummy, tmp;
dummy.next = null;
while(l1 != null || l2 != null) {
if(l1 == null || l2 == null) {
if(l1 != null) {
tail.next = l1;
} else {
tail.next = l2;
}
break;
} else {
if(l1.val <= l2.val) {
tmp = l1;
l1 = l1.next;
} else {
tmp = l2;
l2 = l2.next;
}
}
tail.next = tmp;
tail = tail.next;
tail.next = null;
}
return dummy.next;
}
}
// @lc code=end