手机版
你好,游客 登录 注册
背景:
阅读新闻

单向链表归并排序 Java

[日期:2014-04-10] 来源:Linux社区  作者:卢留雨 [字体: ]

单向链表归并排序 use Java

链表的关键在于递归的时候中间位置的确定,方法是:用两个指针p,f 遍历链表,p走一步而f走两步;当f走完的时候p走到链表的一半!

这让我烧绳子那道逻辑题。

代码如下

/**
 * Definition for singly-linked list.
 * class ListNode {
 *    int val;
 *    ListNode next;
 *    ListNode(int x) {
 *        val = x;
 *        next = null;
 *    }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
       
        if (head == null || head.next == null){
            return head;
        }
       
        ListNode p = head;
        ListNode f = head.next;
        while ( f.next !=null && f.next.next !=null ){//locate p at half of the ListNode
            p = p.next;
            f = f.next.next;
        }
       
        ListNode h2 = sortList(p.next);
        p.next = null;
       
        return merge( sortList (head) , h2 );
       
    }
   
    public ListNode merge(ListNode h1,ListNode h2){
       
        ListNode hn = new ListNode(-1);
        ListNode c = hn;
       
        while (h1 != null && h2 != null ){
            if (h1.val <= h2.val){
                c.next = h1;
                h1 = h1.next;
            }else {
                c.next = h2;
                h2 = h2.next;
            }
            c = c.next;
        }
       
        if(h1 == null){
            c.next = h2;
        }else{
            c.next = h1;
        }
       
        return hn.next;
       
    }
}

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款