题目描述(Easy)
合并两个无序链表成为有序链表
https://leetcode.com/problems/insertion-sort-list/submissions/
https://leetcode.com/problems/sort-list/submissions/
https://leetcode.com/problems/merge-two-sorted-lists/submissions/
算法分析
先排序,再合并。
插入排序:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (!head) return head;
ListNode* fake = new ListNode(-1);
ListNode *p1 = head;
while(p1) {
ListNode *p2 = p1, *p3 = fake;
p1 = p1->next;
while (p3->next != nullptr && p2->val > p3->next->val) {
p3 = p3->next;
}
p2->next = p3->next;
p3->next = p2;
}
return fake->next;
}
};
归并排序:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
// 找到中间节点
ListNode* fast = head, *slow = head;
while (fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
// 中间断开
fast = slow->next;
slow->next = nullptr;
ListNode* head1 = sortList(fast);
ListNode* head2 = sortList(head);
return mergeList(head1, head2);
}
ListNode* mergeList(ListNode* head1, ListNode* head2) {
ListNode* dummy = new ListNode(-1);
ListNode* temp = dummy;
while (head1 && head2) {
if (head1->val < head2->val)
{
temp->next = head1;
head1 = head1->next;
} else {
temp->next = head2;
head2 = head2->next;
}
temp = temp->next;
}
if (head1) {
temp->next = head1;
}
if (head2) {
temp->next = head2;
}
return dummy->next;
}
};
调用stl排序:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool nodeListCmp(ListNode* l1, ListNode* l2) {
return l1->val < l2->val;
}
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head) return head;
vector<ListNode*> nodeList;
while(head) {
nodeList.push_back(head);
head = head->next;
}
sort(nodeList.begin(), nodeList.end(), nodeListCmp);
ListNode* newHead = nodeList[0], *temp = newHead;
for (int i = 1; i < nodeList.size(); ++i) {
temp->next = nodeList[i];
temp = temp->next;
}
temp->next = nullptr;
return newHead;
}
};
合并链表:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
ListNode* fake = new ListNode(-1);
ListNode* cur = fake;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
while (l1) {
cur->next = l1;
l1 = l1->next;
cur = cur->next;
}
while (l2) {
cur->next = l2;
l2 = l2->next;
cur = cur->next;
}
return fake->next;
}
};