1 题目
链表排序
2 解法
2.1 冒泡排序
/*** struct ListNode {* int val;* struct ListNode *next;* };*/class Solution {
public:/*** * @param head ListNode类 * @return ListNode类*/ListNode* sortList(ListNode* head) {// write code hereif (head) {ListNode* endNode = NULL;while (head != endNode) {ListNode* p = head;for (; p->next != endNode; p = p->next) {if (p->next->val < p->val) {int tmp = p->next->val;p->next->val = p->val;p->val = tmp;}}endNode = p;}}return head;}
};
性能一般:
2.2 选择排序
/*** struct ListNode {* int val;* struct ListNode *next;* };*/class Solution {
public:/*** * @param head ListNode类 * @return ListNode类*/ListNode* sortList(ListNode* head) {// write code hereif (head) {ListNode* startNode = head;while (startNode) {ListNode* switchNode = NULL;int min_value = startNode->val;for (auto p = startNode; p; p = p->next) {if (p->val < min_value) {min_value = p->val;switchNode = p;}}if (switchNode) {int tmp = switchNode->val;switchNode->val = startNode->val;startNode->val = tmp;}startNode = startNode->next;}}return head;}
};
性能同样一般:
2.3 插入排序
/*** struct ListNode {* int val;* struct ListNode *next;* };*/class Solution {
public:/*** * @param head ListNode类 * @return ListNode类*/ListNode* sortList(ListNode* head) {// write code hereif (head) {ListNode* inorderList = NULL;ListNode* unorderList = head;while (unorderList) {ListNode* firstUnorderedNode =getFirstUnorderedNode(unorderList);insertToOrderedList(inorderList, firstUnorderedNode);}head = inorderList;}return head;}ListNode* getFirstUnorderedNode(ListNode* &unorderedList) {ListNode* firstNode = unorderedList;unorderedList = unorderedList->next;firstNode->next = NULL;return firstNode;}void insertToOrderedList(ListNode* &orderedList, ListNode* &targetNode) {if (!orderedList || targetNode->val <= orderedList->val) {targetNode->next = orderedList;orderedList = targetNode;} else {ListNode* p = orderedList;while (p->next && p->next->val < targetNode->val) {p = p->next;}targetNode->next = p->next;p->next = targetNode;}}
};
性能好差劲: