spider68

insertion sort linked list

May 27th, 2020
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. void sort(ListNode* &head,ListNode*cur)
  2.     {
  3.         if(head==NULL||cur->val<=head->val)
  4.         {
  5.             cur->next=head;
  6.             head=cur;
  7.         }
  8.         else{
  9.             ListNode*tmp=head;
  10.             while(tmp->next&&tmp->next->val<cur->val)
  11.             {
  12.                 tmp=tmp->next;
  13.             }
  14.             cur->next=tmp->next;
  15.             tmp->next=cur;
  16.         }
  17.     }
  18.     ListNode* insertionSortList(ListNode* head) {
  19.         ListNode*tmp=head,*root=NULL;
  20.         while(tmp)
  21.         {
  22.             ListNode*next=tmp->next;
  23.             sort(root,tmp);
  24.             tmp=next;
  25.         }
  26.         return root;
  27.     }
Add Comment
Please, Sign In to add comment