题解 | #链表的插入排序#

链表的插入排序

https://www.nowcoder.com/practice/152bc6c5b14149e49bf5d8c46f53152b

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */

class Solution {
  public:
    /**
     *
     * @param head ListNode类
     * @return ListNode类
     */
    ListNode* insertionSortList(ListNode* head) {
        // write code here
        ListNode* sorted = nullptr; // 新的排序链表

        while (head) {
            ListNode* current = head; // 当前节点
            head = head->next; // 移动原链表的指针

            sorted = sortedInsert(sorted, current); // 插入到排序链表
        }

        return sorted;
    }
  private:
    ListNode* sortedInsert(ListNode* head, ListNode* newNode) {
        if (!head || newNode->val < head->val) {
            newNode->next = head;
            return newNode; // 新节点成为头
        }

        ListNode* current = head;
        while (current->next && current->next->val < newNode->val) {
            current = current->next; // 找到插入位置
        }

        newNode->next = current->next; // 插入新节点
        current->next = newNode;

        return head;
    }
};

全部评论

相关推荐

昨天 08:46
已编辑
门头沟学院 C++
只写bug的程序媛:本科能找到好的,真不建议读研,提前占坑比较好,本科找不到好的,也不建议读研,因为两三年之后压力只会更大,唯一的解就是行业好起来
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务