LeetCode——Insertion Sort List

Question

Sort a linked list using insertion sort.

Solution

我的解法,假设第一个节点都比其他节点小,这样感觉好移动指针一些,所以添加了一个额外的最小的节点。

Code

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if (head == NULL)
            return head;

        ListNode* first = new ListNode(INT_MIN);
        first->next = head;
        head = first;

        ListNode* p2 = head->next;
        ListNode* p2pre = p2;
        while (p2) {
            ListNode* p1 = head;
            ListNode* p1pre = p1;
            while (p1 != p2) {
                if (p1->val > p2->val) {
                	p2pre->next = p2->next;
                    p1pre->next = p2;
                    p2->next = p1;
                    p2 = p2pre;
                    break;
                } else {
                    p1pre = p1;
                    p1 = p1->next;
                }


            }
            p2pre = p2;
            p2 = p2->next;
        }

        return head->next;
    }
};

相关文章:

  • 2021-06-15
  • 2021-08-24
  • 2021-11-27
  • 2021-10-18
  • 2022-02-05
  • 2022-01-15
  • 2022-02-25
猜你喜欢
  • 2021-12-03
  • 2021-07-04
  • 2021-07-02
  • 2022-12-23
  • 2021-09-11
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案