Description:
题目大意:排序单链表元素
解题思路:方法一:(更优)
算法标签:sort 排序
- 存储链表元素
- 直接排序
- 赋值原来的链表
代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
ListNode* sortInList(ListNode* head) {
vector<int>number;
ListNode* dummyhead = head;
while(dummyhead != NULL) {
number.push_back(dummyhead -> val);
dummyhead = dummyhead -> next;
}
sort(number.begin(),number.end());
dummyhead = head;
for(int i = 0;i < number.size();i++) {
dummyhead -> val = number[i];
dummyhead = dummyhead -> next;
}
return head;
}
};
解题思路:方法二:
算法标签:归并排序
代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
ListNode* sortInList(ListNode* head) {
if((head == NULL) || (head -> next == NULL))
return head;
// 使用快慢指针寻找链表的中点
ListNode* fast = head -> next;
ListNode* slow = head;
while(fast != NULL && fast -> next != NULL) {
slow = slow -> next;
fast = fast -> next -> next;
}
// 断开链表
ListNode* mid = slow -> next;
slow -> next = NULL;
// 递归左右两边进行排序
ListNode* left = sortInList(head);
ListNode* right = sortInList(mid);
// 创建新链表
ListNode* temp = new ListNode(0);
ListNode* res = temp;
// 合并 left 和 right 两个链表
while(left != NULL && right != NULL) {
if(left -> val <= right -> val) {
temp -> next = left;
left = left -> next;
}
else {
temp -> next = right;
right = right -> next;
}
temp = temp -> next;
}
if(left != NULL) {
temp -> next = left;
}
else
temp -> next = right;
return res -> next;
}
};