package Leetcode_LinkedList; /** * 题目: * Sort a linked list in O(n log n) time using constant space complexity. * Example 1: * Input: 4->2->1->3 * Output: 1->2->3->4 * Example 2: * Input: -1->5->3->4->0 * Output: -1->0->3->4->5 * 解题思路: * 找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge */ public class SortList_148_1014 { public ListNode SortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode slow = head; ListNode fast = head; ListNode pre = null; //找到链表的中间结点 while (fast != null && fast.next != null) { pre = slow; slow = slow.next; fast = fast.next.next; } pre.next = null; //对链表的前半部分和后半部分分别进行排序 ListNode list1 = SortList(head); ListNode list2 = SortList(slow); return Merge(list1, list2); } //将两个排序好的链表进行合并 public ListNode Merge(ListNode list1, ListNode list2) { ListNode result = new ListNode(-1); ListNode temp = result; while (list1 != null && list2 != null) { if (list1.val < list2.val) { temp.next = list1; list1 = list1.next; }else { temp.next = list2; list2 = list2.next; } temp = temp.next; } if (list1 != null) { temp.next = list1; } if (list2 != null) { temp.next = list2; } return result.next; } public static void main(String[] args) { ListNode node1 = new ListNode(4); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(1); ListNode node4 = new ListNode(3); node1.next = node2; node2.next = node3; node3.next = node4; SortList_148_1014 test = new SortList_148_1014(); ListNode result = test.SortList(node1); while (result != null) { System.out.print(result.val + " "); result = result.next; } } }
leetcode:(148) sort list (java)
最新推荐文章于 2022-01-25 10:00:23 发布