/**
* 单链表的排序
* 归并排序的基本思想:找到链表的中间节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行合并
* @author cfp008
*
*/
public class SortList
{
class ListNode
{
int val;
ListNode next;
ListNode(int x)
{
val = x;
next = null;
}
}
public ListNode sort(ListNode head)
{
if(head == null || head.next == null)
{
return head;
}
ListNode _middle = getMiddleNode(head);//找到单链表的中间节点
ListNode _next = _middle.next;
_middle.next = null;
return mergeList(sort(head), sort(_next));
}
/**
* 利用快慢指针的思想找中间节点,快指针的速度是慢指针的两倍
* @param head
* @return
*/
public ListNode getMiddleNode(ListNode head)
{
ListNode _slow = head;//慢指针
ListNode _fast = head;//快指针
while(_fast.next != null && _fast.next.next != null)
{
_slow = _slow.next;
_fast = _fast.next.next;
}
return _slow;
}
public ListNode mergeList(ListNode a, ListNode b)
{
if(a == null)
{
return b;
}
if(b == null)
{
return a;
}
ListNode _head = new ListNode(-1);
ListNode _curr = _head;
while(a != null && b != null)
{
if(a.val <= b.val)
{
_curr.next = a;
a = a.next;
}
else
{
_curr.next = b;
b = b.next;
}
_curr = _curr.next;
}
_curr.next = (a != null)? a : b;
return _head.next;
}
}
* 单链表的排序
* 归并排序的基本思想:找到链表的中间节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行合并
* @author cfp008
*
*/
public class SortList
{
class ListNode
{
int val;
ListNode next;
ListNode(int x)
{
val = x;
next = null;
}
}
public ListNode sort(ListNode head)
{
if(head == null || head.next == null)
{
return head;
}
ListNode _middle = getMiddleNode(head);//找到单链表的中间节点
ListNode _next = _middle.next;
_middle.next = null;
return mergeList(sort(head), sort(_next));
}
/**
* 利用快慢指针的思想找中间节点,快指针的速度是慢指针的两倍
* @param head
* @return
*/
public ListNode getMiddleNode(ListNode head)
{
ListNode _slow = head;//慢指针
ListNode _fast = head;//快指针
while(_fast.next != null && _fast.next.next != null)
{
_slow = _slow.next;
_fast = _fast.next.next;
}
return _slow;
}
public ListNode mergeList(ListNode a, ListNode b)
{
if(a == null)
{
return b;
}
if(b == null)
{
return a;
}
ListNode _head = new ListNode(-1);
ListNode _curr = _head;
while(a != null && b != null)
{
if(a.val <= b.val)
{
_curr.next = a;
a = a.next;
}
else
{
_curr.next = b;
b = b.next;
}
_curr = _curr.next;
}
_curr.next = (a != null)? a : b;
return _head.next;
}
}