LeetCode Sort List 解题报告

http://blog.csdn.net/worldwindjp/article/details/18986737


Sort a linked list in O(n log n) time using constant space complexity.
http://oj.leetcode.com/problems/sort-list/


解题报告:就是对一个链表进行归并排序。
主要考察3个知识点,
知识点1:归并排序的整体思想
知识点2:找到一个链表的中间节点的方法
知识点3:合并两个已排好序的链表为一个新的有序链表

归并排序的基本思想是:找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge。

AC代码: https://github.com/tanglu/Leetcode/blob/master/sortList.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { 
  7.  *         val = x; 
  8.  *         next = null; 
  9.  *     } 
  10.  * } 
  11.  */  
  12. public class Solution {  
  13.      //use the fast and slow pointer to get the middle of a ListNode  
  14.      ListNode getMiddleOfList(ListNode head) {  
  15.         ListNode slow = head;  
  16.         ListNode fast = head;  
  17.         while(fast.next!=null&&fast.next.next!=null) {  
  18.             slow = slow.next;  
  19.             fast = fast.next.next;  
  20.         }  
  21.         return slow;  
  22.     }  
  23.       
  24.     public ListNode sortList(ListNode head) {  
  25.         if(head==null||head.next==null) {  
  26.             return head;  
  27.         }  
  28.         ListNode middle = getMiddleOfList(head);  
  29.         ListNode next   = middle.next;  
  30.             middle.next = null;  
  31.         return mergeList(sortList(head), sortList(next));  
  32.     }  
  33.       
  34.     //merge the two sorted list  
  35.     ListNode mergeList(ListNode a, ListNode b) {  
  36.         ListNode dummyHead = new ListNode(-1);  
  37.         ListNode curr = dummyHead;  
  38.         while(a!=null&&b!=null) {  
  39.             if(a.val<=b.val) {  
  40.                 curr.next=a;a=a.next;  
  41.             } else {  
  42.                 curr.next=b;b=b.next;  
  43.             }  
  44.             curr  = curr.next;  
  45.         }  
  46.         curr.next = a!=null?a:b;  
  47.         return dummyHead.next;  
  48.     }  
  49. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值