您的位置:首页 > 编程语言 > Java开发

leetCode练习(148)

2017-03-06 20:38 351 查看
题目:Sort List
难度:MEDIUM
问题描述:

Sort a linked list in O(n log n) time using constant space complexity.

Subscribe to see which companies asked this question.

解题思路:使用归并排序即可。注意模块化。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
int len = this.length(head);
return guibing(head,len);
}
private ListNode guibing(ListNode head,int len){
ListNode[] lists;
if(len==0){
return head;
}
if(len==1){
return head;
}else{
lists=this.sperate(head,len);
lists[0]=guibing(lists[0],len/2);
lists[1]=guibing(lists[1],len-len/2);
head=concat(lists[0],lists[1]);
}
return head;
}
private ListNode concat(ListNode first,ListNode second){
ListNode head=new ListNode(-1);
ListNode temp=head;
while(first!=null && second!=null){
if(first.val<second.val){
temp.next=first;
temp=temp.next;
first=first.next;
}else{
temp.next=second;
temp=temp.next;
second=second.next;
}
}
if(first==null){
temp.next=second;
}else{
temp.next=first;
}
return head.next;
}
private int length(ListNode head){
int len;
if(head==null){
len=0;
}else{
len = 1;
while(head.next!=null){
head = head.next;
len++;
}
}
return len;
}
private ListNode[] sperate(ListNode head,int len){
int mid=len/2;
ListNode[] res = new ListNode[2];
ListNode temp=head;
for(;mid>1;mid--){
temp=temp.next;
}
res[1]=temp.next;
temp.next=null;
res[0]=head;
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 算法