Sort_List
在LeetCode 里面,因为只有归并排序的时间复杂度为O(1),所以快速排序用不了,前面两个都没用直接看最后一个归并排序。
冒泡排序(超时了)
public ListNode sortList(ListNode head) {
if(null == head)
return head;
int counter = 0;
ListNode current = head;
while (null != current.next) {
current = current.next;
counter++;
}
current = head;
int pre;
while (counter > 0) {
for (int i = 0; i < counter; i++) {
if (current.val > current.next.val) {
pre = current.val;
current.val = current.next.val;
current.next.val = pre;
}
current = current.next;
}
current = head;
counter--;
}
return head;
}
快速排序(在leetcode 上面还是超时间了)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
quickSort(head, null);
return head;
}
public static ListNode quickSort(ListNode head, ListNode end) {
if (head != end) {
ListNode p1 = head;
ListNode p2 = head.next;
//走到末尾才停
while (p2 != null) {
//大于key值时,p1向前走一步,交换p1与p2的值
if ((p2.val < head.val) && (p1 != p2)) {
p1 = p1.next;
int temp = p1.val;
p1.val = p2.val;
p2.val = temp;
}
p2 = p2.next;
}
//当有序时,不交换p1和key值
if (p1 != head) {
int temp = p1.val;
p1.val = head.val;
head.val = temp;
}
quickSort(head, p1);
quickSort(p1.next, null);
return p1;
}
return head;
}
}
归并排序
思路:https://blog.csdn.net/mine_song/article/details/69831827
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (null == head || null == head.next) {
return head;
}
ListNode mid = getMidNode(head);
ListNode right = mid.next;
mid.next = null;
return mergeSort(sortList(head), sortList(right));
}
static ListNode getMidNode(ListNode node) {
ListNode fast = node;
ListNode slow = node;
while (null != fast.next && null != fast.next.next) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
static ListNode mergeSort(ListNode head1, ListNode head2) {
ListNode p1 = head1;
ListNode p2 = head2;
ListNode head;
if (p1.val < p2.val) {
head = p1;
p1 = p1.next;
} else {
head = p2;
p2 = p2.next;
}
ListNode p = head;
while (null != p1 && null != p2) {
if (p1.val <= p2.val) {
p.next = p1;
p1 = p1.next;
p = p.next;
} else {
p.next = p2;
p2 = p2.next;
p = p.next;
}
}
if (null != p1) {
p.next = p1;
}
if (null != p2) {
p.next = p2;
}
return head;
}
}