leetcode---Insertion Sort List

来源:互联网 发布:手机开淘宝店怎么注册 编辑:程序博客网 时间:2024/06/09 13:23

Sort a linked list using insertion sort.

/** * 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 == NULL)            return NULL;         ListNode *start = new ListNode(0);         ListNode *cur = head;         while(cur)         {             ListNode *pre = start;             while(pre->next && cur->val > pre->next->val)             {                 pre = pre->next;             }             ListNode *next = cur->next;             cur->next = pre->next;             pre->next = cur;             cur = next;         }         return start->next;    }};
0 0
原创粉丝点击