Insert sort on linked list elements
Example 1:
Input: 4->2->1->3 output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 output: -1->0->3->4->5
Problem Solving Ideas:
For the element to be sorted, locate the appropriate position in the first part of the ordered list.
Such as
To sort the node 2, simply insert it between Node 1 and Node 3.
From the starting point, traverse to find the first node greater than Node 2, and Insert Node 2 in front of the node.
Defines two pointers p,q, Q points to the previous node of the node to be sorted, p is used to find the first node that is larger than the node to be sorted
The p,q pointer can be borrowed to insert node 2 before node 3.
Implementation code:
Public StaticListNode insertionsortlist (ListNode head) {ListNode First=NewListNode (0); First.next=Head; ListNode P=First ; ListNode Q=Head; ListNode temp; while(Q.next! =NULL) {p=First ; while(p!=q && p.next.val<q.next.val) p =P.next; if(P! =q) {temp=Q.next; Q.next=Temp.next; Temp.next=P.next; P.next=temp; } ElseQ =Q.next; } returnFirst.next; }
Inserting a list into a sort