题目描述
给定一个无序单链表,实现单链表的排序(按升序排序)。
输入
[1,3,2,4,5]
返回值
{1,2,3,4,5}
public class SortInListME {
public static void main(String[] args) {
ListNode l1 = new ListNode(1); // 1,3,2,5,4
ListNode l2 = new ListNode(3);
ListNode l3 = new ListNode(2);
ListNode l4 = new ListNode(5);
ListNode l5 = new ListNode(4);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
SortInListME sortInListME = new SortInListME();
ListNode resutl = sortInListME.sortInList2(l1);
sortInListME.printList(resutl);
}
public void printList(ListNode head) {
ListNode curNode = head;
//循环遍历到尾节点
while (curNode != null) {
System.out.print(curNode.val + " ");
curNode = curNode.next;
}
System.out.println();
}
/*
* 递归将链表分为两部分,每部分排好序以后,合并这两个排好序的链表即可
*/
public ListNode sortInList2 (ListNode head) {
// write code here
if (null == head || head.next == null) {
return head;
}
ListNode p1 = head;
ListNode p2 = head.next; // 1,3,2,5,4
while (p2 != null && p2.next != null) {
p1 = p1.next;
p2 = p2.next.next;
}
ListNode p2Head = sortInList2(p1.next);
p1.next = null;
ListNode p1Head = sortInList2(head);
ListNode pre = new ListNode(0);
ListNode ansPre = pre;
while (p1Head != null && p2Head != null) {
if (p1Head.val < p2Head.val) {
pre.next = p1Head;
p1Head = p1Head.next;
} else {
pre.next = p2Head;
p2Head = p2Head.next;
}
pre = pre.next;
}
pre.next = p1Head == null ? p2Head : p1Head;
return ansPre.next;
}
/**
* 下面的方法,只能替换节点中的值,不能替换实际的节点
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
int temp;
ListNode curNode = head;
while(null != curNode){
// 内循环从当前节点的下一个节点开始
ListNode nextNode = curNode.next;
while(null != nextNode){
if(nextNode.val < curNode.val){
temp = curNode.val;
curNode.val = nextNode.val;
nextNode.val = temp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
}