Title:

Sort a linked list using insertion sort.

 

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        ListNode* sortedHead = new ListNode(0);
        while (head){
            ListNode* cur = sortedHead;
            ListNode* tmp = head->next;
            while (cur->next != NULL && cur->next->val < head->val){
                cur = cur->next;
            }
            head->next = cur->next;
            cur->next = head;
            head = tmp;
        }
        return sortedHead->next;
    }
};

 

相关文章:

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