[Leetcode]#147 Insertion Sort List

来源:互联网 发布:淘宝蛋白粉真假 编辑:程序博客网 时间:2024/04/27 22:42
//#147 Insertion Sort List//80ms 81.07%#include <iostream>using namespace std;/** * 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)     //"insertion sort"    {        if(head == NULL || head->next == NULL) return head;        //after this point, all in coming linked lists have a size of 2 or more        ListNode *p, *next_p, *n;        //ListNode *end,        //end = head;        p = head->next;        next_p = p->next;        head->next = NULL;        //end->next = NULL;        while(p != NULL)        {            //cout << "L0 ";            p->next = NULL;            if(head->val > p->val)            {                p->next = head;                head = p;            }            else            {                n = head;                while(n->next != NULL)                {                    //cout << "L1 ";                    if(n->next->val > p->val)                    {                        p->next = n->next;                        n->next = p;                        break;                    }                    n = n->next;                }                n->next = p;            }            //insertion finished            //prepare for next item            p = next_p;            if(next_p != NULL)            {                next_p = next_p->next;            }            //list_print(head);        }        return head;            }};
0 0
原创粉丝点击