LeetCode148. 排序链表
题目描述
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
排序链表
提示:
链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105
一、解题关键词
链表遍历
二、解题报告
1.思路分析
1、想到放饭list 进行排序 再放到链表里面(时间空间都浪费)
2、双指针 找到长度和中间位置 、
3、拆分成两个链表
4、归并排序
2.时间复杂度
3.代码示例
/**
* 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;
}
ListNode merge( ListNode list1 , ListNode list2){
ListNode dummyHead = new ListNode(0);
ListNode tmp = dummyHead,tmp1 = list1,tmp2 = list2;
while(tmp1 != null && tmp2 != null){
if(tmp1.val <= tmp2.val){
tmp.next = tmp1.next;
tmp1 = tmp1.next;
}else{
tmp.next = tmp2;
tmp2 = tmp2.next;
}
tmp = tmp.next;
}
if(tmp1 != null){
tmp.next = tmp1;
}else if(tmp2 != null){
tmp.next = tmp2;
}
return dummyHead.next;
}
}
2.知识点
本文详细介绍了如何使用归并排序算法对链表进行排序。首先通过双指针找到链表的中间节点,然后将链表拆分为两部分分别进行排序,最后通过归并操作将排序后的链表合并。这种方法避免了将链表转换为数组再排序,提高了效率。
1370

被折叠的 条评论
为什么被折叠?



