Title: Sort a linked list using insertion Sort.
Sort the linked list even with an insert sort.
Thinking Analysis:
Insert sort idea See "sort (i): Direct Insert Sort"
C + + Reference code:
/** * 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)returnNullptr//previous remembers the previous node of the current node (because a single-linked list must know the previous node of the current node when inserting)ListNode *previous = head;The //current node is the node to be inserted into the previously sequenced nodeListNode *current = head->next; while(current) {The //small and big pointers are used to record pointers that are smaller than current and larger than current, and small and big are adjacentListNode *small = nullptr; ListNode *big = head; while(big->Val< current->Val) {small = big; Big = big->next; }//If big!=current indicates that the current node should be inserted between the small and the big node if(Big! = current) {Previous->next = current->next;if(small) Small->next = current;Elsehead = current; Current->next = big; }//If Big=current then previous means the next node is OK Else{previous = previous->next; }//Last current node points to previous the next node is current one step forwardCurrent = previous->next; }returnHead }};
Java Reference Code:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode ( int x) {* val = x; * next = NULL; *} *} */ Public class solution { PublicListNodeinsertionsortlist(ListNode head) {if(Head = =NULL)return NULL; ListNode previous = head; ListNode current = Head.next; while(Current! =NULL) {ListNode small =NULL; ListNode big = head;//Find the big and small elements in the current, big and small adjacent while(Big.val < Current.val) {small = big; Big = Big.next; }//If big!=current is inserted between small and big if(Big! = current) {previous.next = Current.next;if(Small! =NULL) Small.next = current;Elsehead = current; Current.next = big; }Else{previous = Previous.next; } current = Previous.next; }returnHead }}
Leetcode:insertion Sort List