/**注意往链表头插入元素的情况
 * 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)||(head->next==NULL)) return head;
        ListNode *res=head;
        head = head->next;
        res->next=NULL;
       
        while(head){
            ListNode *p=res;
            while(p->next && (p->next->val) <= (head->val)){
               p=p->next;
            }
            if((p->val) > (head->val)){                  //这几个要注意顺序
                ListNode *temp = head->next;
                head->next=p;
                res=head;
                head=temp;
                
            }
            else{                                          //注意顺序
            
            ListNode *temp = p->next;
            p->next=head;
            head=head->next;
            p->next->next=temp;
            }
            
            }
        return res;
        }
};

 

相关文章:

  • 2021-06-25
  • 2022-01-02
  • 2021-08-28
  • 2022-12-23
  • 2021-07-09
  • 2022-12-23
  • 2022-01-09
猜你喜欢
  • 2021-11-26
  • 2021-12-12
  • 2021-05-20
  • 2021-05-26
  • 2021-11-02
  • 2022-03-07
相关资源
相似解决方案