当前位置: 首页 > 文档资料 > LeetCode 题解 >

Linked List - Sort List

优质
小牛编辑
128浏览
2023-12-01

Sort a linked list in O(n log n) time using constant space complexity.

这题要求我们对链表进行排序,我们可以使用divide and conquer的方式,依次递归的对链表左右两半进行排序就可以了。代码如下:

  1. class Solution {
  2. public:
  3. ListNode *sortList(ListNode *head) {
  4. if(head == NULL || head->next == NULL) {
  5. return head;
  6. }
  7. ListNode* fast = head;
  8. ListNode* slow = head;
  9. //快慢指针得到中间点
  10. while(fast->next && fast->next->next) {
  11. fast = fast->next->next;
  12. slow = slow->next;
  13. }
  14. //将链表拆成两半
  15. fast = slow->next;
  16. slow->next = NULL;
  17. //左右两半分别排序
  18. ListNode* p1 = sortList(head);
  19. ListNode* p2 = sortList(fast);
  20. //合并
  21. return merge(p1, p2);
  22. }
  23. ListNode *merge(ListNode* l1, ListNode* l2) {
  24. if(!l1) {
  25. return l2;
  26. } else if (!l2) {
  27. return l1;
  28. } else if (!l1 && !l2) {
  29. return NULL;
  30. }
  31. ListNode dummy(0);
  32. ListNode* p = &dummy;
  33. while(l1 && l2) {
  34. if(l1->val < l2->val) {
  35. p->next = l1;
  36. l1 = l1->next;
  37. } else {
  38. p->next = l2;
  39. l2 = l2->next;
  40. }
  41. p = p->next;
  42. }
  43. if(l1) {
  44. p->next = l1;
  45. } else if(l2){
  46. p->next = l2;
  47. }
  48. return dummy.next;
  49. }
  50. };

Insertion Sort List

Sort a linked list using insertion sort.

这题要求我们使用插入排序的方式对链表进行排序,假设一个链表前n个节点是有序,第n + 1的节点需要遍历前n个,插入到合适位置就可以了。

代码如下:

  1. class Solution {
  2. public:
  3. ListNode *insertionSortList(ListNode *head) {
  4. if(head == NULL || head->next == NULL) {
  5. return head;
  6. }
  7. ListNode dummy(0);
  8. ListNode* p = &dummy;
  9. ListNode* cur = head;
  10. while(cur) {
  11. p = &dummy;
  12. while(p->next && p->next->val <= cur->val) {
  13. p = p->next;
  14. }
  15. ListNode* n = p->next;
  16. p->next = cur;
  17. cur = cur->next;
  18. p->next->next = n;
  19. }
  20. return dummy.next;
  21. }
  22. };