[LeetCode] 148. 排序链表
Posted ACBingo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
}
}
以上是关于[LeetCode] 148. 排序链表的主要内容,如果未能解决你的问题,请参考以下文章