Skip to content

Commit

Permalink
2023/4/17
Browse files Browse the repository at this point in the history
  • Loading branch information
KidJoe1412 committed Apr 17, 2023
1 parent 66f18db commit d67bdb2
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/leetcode/Q148.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package leetcode;

import java.util.List;

/**
* 题干:排序链表
* 给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
* ******************************************************
* 解法:归并排序
* ******************************************************
* 原题:<a href="https://leetcode.cn/problems/sort-list/description/"></a>
* ******************************************************
*/
class Q148 {
public ListNode sortList(ListNode head) {
// 跳出条件
if (head == null || head.next == null)
return head;
// 找中点
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode start = slow.next;
slow.next = null;
// 递归
ListNode l1 = sortList(head);
ListNode l2 = sortList(start);
// 合并
ListNode ans = merge(l1, l2);
return ans;

}
public ListNode merge(ListNode l1,ListNode l2){
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (l1.val < l2.val){
l1.next = merge(l1.next,l2);
return l1;
}else {
l2.next = merge(l2.next,l1);
return l2;
}
}
}




















0 comments on commit d67bdb2

Please sign in to comment.