首页 > 代码库 > LeetCode - Sort List
LeetCode - Sort List
就是用List来实现merge sort.
import java.io.*; import java.util.*; class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } static ListNode initializeLinkList(ArrayList<Integer> arrList){ ListNode head = new ListNode(arrList.get(0)); ListNode cNode = head; for(int i=1;i<arrList.size();i++) { cNode.next = new ListNode(arrList.get(i)); cNode = cNode.next; } return head; } static void showList(ListNode head) { while(head != null) { System.out.println(head.val); head = head.next; } } } public class Solution { public ListNode medianNode(ListNode head) { ListNode osNode = head; ListNode tsNode = head; while(tsNode.next != null && tsNode.next.next !=null) { osNode = osNode.next; tsNode = tsNode.next.next; } return osNode; } public ListNode mergeList(ListNode head1, ListNode head2) { if(head1 == null) return head2; else if(head2 == null) return head1; ListNode head = null, cnode = null; if(head1.val < head2.val) { head = head1; head1 = head1.next; } else { head = head2; head2 = head2.next; } cnode = head; while(head1 != null && head2 != null) { if(head1.val < head2.val) { cnode.next = head1; head1 = head1.next; } else { cnode.next = head2; head2 = head2.next; } cnode= cnode.next; } while(head1 != null) { cnode.next = head1; cnode = cnode.next; head1 = head1.next; } while(head2 != null) { cnode.next = head2; cnode = cnode.next; head2 = head2.next; } return head; } public ListNode sortList(ListNode head) { if(head == null || head.next == null) return head; ListNode mNode = medianNode(head); ListNode head1 = head; ListNode head2 = mNode.next; mNode.next = null; head1 = sortList(head1); head2 = sortList(head2); head = mergeList(head1,head2); return head; } }
LeetCode - Sort List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。