leetcode题目
sort-list
题目描述
Sort a linked list in O(n log n) time using constant space complexity.
思路
由于时间复杂度要求o(n Log n),空间复杂度要求固定,则需要使用归并排序
注意事项:
1、分解链表时,获取中间节点后,可以把中间节点的next指向null,便于后续获取中间节点及归并处理
2、合并两个有序链表时,可定义要返回的新链表的头节点的pre节点,避免确定新链表头节点时的比较操作
代码
package com.leetcode.list;
/**
* sort-list
* 题目描述:
* Sort a linked list in O(n log n) time using constant space complexity.
*/
public class SortedList {
static class ListNode{
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
@Override
public String toString() {
if (this.next == null) {
return String.valueOf(this.val);
}
return this.val + "->" + this.next.toString();
}
}
/**
* 思路:
* 由于时间复杂度要求o(n Log n),空间复杂度要求固定
* 则需要使用归并排序
*
*
* @param head 头节点
* @return 排序后链表的头节点
*/
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = getMid(head);
ListNode another;
if (mid == null) {
another = null;
} else {
another = mid.next;
// 变原链表为两个独立的链表,很巧妙
mid.next = null;
}
return mergeSortedList(sortList(head), sortList(another));
}
// 合并两个有序链表为一个链表
private ListNode mergeSortedList(ListNode first, ListNode second) {
if (first == null && second == null) {
return null;
}
if (first == null) {
return second;
}
if (second == null) {
return first;
}
// 虚拟一个head的前缀节点,避免前缀额外的操作确定头节点
ListNode pre = new ListNode(0);
ListNode curNode = pre;
ListNode cur1 = first;
ListNode cur2 = second;
while (cur1 != null && cur2 != null) {
if (cur1.val <= cur2.val) {
curNode.next = cur1;
cur1 = cur1.next;
} else {
curNode.next = cur2;
cur2 = cur2.next;
}
curNode = curNode.next;
}
// 处理剩余的元素
if (cur1 != null) {
curNode.next = cur1;
}
if (cur2 != null) {
curNode.next = cur2;
}
return pre.next;
}
// 获取链表的中间节点
private ListNode getMid(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public static void main(String[] args) {
ListNode head = createTestLinkedList();
ListNode newHead = new ListNode(13);
newHead.next = head;
System.out.println(newHead);
System.out.println(new SortedList().sortList(newHead));
}
private static ListNode createTestLinkedList() {
ListNode head = new ListNode(0);
ListNode curNode = head;
for (int i = 1; i < 10; i++) {
curNode.next = new ListNode(i);
curNode = curNode.next;
}
return head;
}
}