LeetCode (Insertion Sort List)

xiaoxiao2021-02-28  114

Problem:

Sort a linked list using insertion sort.

Solution:

/** * 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 || !head->next) return head; ListNode l(0), *pre = &l; ListNode *cur = head, *next; while(cur){ next = cur->next; while(pre->next && pre->next->val < cur->val) pre = pre->next; cur->next = pre->next; pre->next = cur; cur = next; pre = &l; } return l.next; } };

转载请注明原文地址: https://www.6miu.com/read-30102.html

最新回复(0)