歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 單向鏈表歸並排序 Java

單向鏈表歸並排序 Java

日期:2017/3/1 9:45:30   编辑: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;

}
}

Copyright © Linux教程網 All Rights Reserved