Simple insert sort, always time out, leave this record for a moment.
Class solution: # @param head, a listnode # @return a listnode def insertionsortlist (self, head): if head = = No NE or head.next = = None:return Headpsuhead = ListNode ( -1) while head:tail = Psuheadheadnext = Head.nextwhile Tail.next and Tail.next.val < Head.val:tail = Tail.nexthead.next = Tail.nexttail.next = Headhead = Headnextreturn Psuhead.next
| Last executed input: |
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,2 |
C++ac's
ListNode *insertionsortlist (ListNode *head) {if (head = = NULL | | head->next = NULL) return head;//sort involves changes in the head node. For convenience, we define an additional pseudo-head node ListNode *psuhead = new ListNode ( -1), while (head) {ListNode *pre = Psuhead; ListNode *tail = psuhead->next;while (tail && tail->val < Head->val) {pre = Tail;tail = Tail->next;} ListNode *nexthead = Head->next;head->next = Pre->next;pre->next = Head;head = NextHead;} Head = Psuhead->next;delete (psuhead); return head;}
[Leetcode] Insertion Sort List (python)