设为首页 加入收藏

TOP

单向链表归并排序 Java
2014-11-23 23:57:10 来源: 作者: 【 】 浏览:6
Tags:单向 归并 排序 Java

单向链表归并排序 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;

}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java内存管理--栈、堆和常量池 下一篇SpringMVC @RequestBody接收Json..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: