147. Insertion Sort List

来源:互联网 发布:幼儿教育软件哪个好 编辑:程序博客网 时间:2024/03/29 10:12

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) {ListNode dummy(INT_MIN);while (head){ListNode* newHead = &dummy;while (newHead->next && head->val > newHead->next->val){//主要需要pre,所以这里是newHead->nextnewHead = newHead->next;}ListNode* next = head->next;ListNode* newNext = newHead->next;newHead->next = head;head->next = newNext;head = next;}return dummy.next;}};


0 0
原创粉丝点击