LeetCode Insertion Sort List

来源:互联网 发布:mac怎么玩最终幻想 编辑:程序博客网 时间:2024/06/05 15:34
/** * 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 = new ListNode(-1);//dummy node;        ListNode* cur = head;//node to be inserted        ListNode* pre=dummy;//node will be inserted between pre and pre->next;        ListNode* next ;//cur->next        while(cur!=NULL){            next=cur->next;            while(pre->next!=NULL&&(pre->next->val<=cur->val)) pre=pre->next;            cur->next = pre->next;            pre->next = cur;            cur=next;            pre=dummy;        }        return dummy->next;    }};

0 0