I'm almost in despair that the time limit exceed again。。。。help


  • 0
    L
    /**
     * 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 *pre,*q,*p,*p1;
            ListNode *head1=head;
           
            if(head1->next!=NULL){  
                 p=head->next;
             //    p1=head->next->next;
                while(p!=NULL) {
                pre->next=head1;
                q=head1;
                while(q!=NULL&&p->val>=q->val){
                    pre=q;
                    q=q->next;
                }
                 p1=p->next;
                    p->next=q;
                    pre->next=p;
                    q=p;
                    p=p1;
                    p1=p1->next;
         /*       if(p->val<q->val&&q!=NULL) {
                    p1=p->next;
                    p->next=q;
                    pre->next=p;
                    q=p;
                    p=p1;
                    p1=p1->next;
                }
                else{
                    pre=q;
                    q=q->next;
                }
             */   
            }
            }
          
            return head1;
        }
    };

  • 0
    S

    IMHO, *pre defines by ListNode *pre without initialization. The first time using it is pre->next=head1; . I cannot understand that how could it work well.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.