Sort a linked list using insertion sort.
The problem is to order the single-linked list in the same way as the insertion sort.
The boundary condition is not considered first:
1. The first node is considered an ordered area, and all subsequent nodes are treated as unordered areas.
2. Start with the second node p, traverse the ordered area, and know the node Q that encounters a greater P-value than the node, and insert the node p before the node Q.
3. Repeat the above steps until the end of the list traversal.
It is important to note that:
1. When traversing an unordered zone, the subsequent nodes of the current node need to be saved to prevent the pointer from being lost.
2. If the Wakahara list is empty, NULL is returned directly.
Put the following code:
/** * Definition forsingly-linked list. * struct ListNode {*intVal * ListNode *Next; * ListNode (intx): Val (x),Next(NULL) {} * }; */classSolution { Public: ListNode *insertionsortlist (ListNode *head) {listnode* first =NewListNode (0); First->Next= head;if(head) {listnode* p = head->Next; Head->Next=NULL; while(p) {listnode* R = p->Next; listnode* q = First; while(q->Next&&q->Next->val < p->val) Q = q->Next; P->Next= q->Next; Q->Next= P; p = r; }} return first->Next; }};
[Leetcode] Insertion Sort