Sort a linked list using insertion sort.
The problem is to use a linked list to do the insertion sort. Although the previous data structure learned the insertion and deletion of linked lists, but those are the simplest basic operation, just give a node, directly give the insertion position.
First of all, the idea of inserting a sort is to insert an element into a sorted, ordered list each time, so first find the element that needs to be inserted, and if the linked order of the linked list is ordered in sequence, direct continue
When the element to be inserted is found, the first element that makes it unordered. The position of the current element should be recorded first, as well as the position before the element.
Next, start traversing the sorted list of previous lists until you find the location you want to insert
Finally, we use the basic operation of the insert that I learned before.
The whole idea is relatively clear, just be sure to remember when to insert the next order of time.
One thing you don't understand is why return to Newhead.next?
Attached below the source code
Public ListNode insertionsortlist (ListNode head) { if (head==null| | Head.next==null) { return head; } ListNode newhead = new ListNode ( -1); Newhead.next = head; ListNode cur = head; ListNode post = Head.next; while (post!=null) { if (post.val>cur.val) { cur = cur.next; Post = Post.next; } else{ ListNode insertcur = newhead; ListNode insertpost = Newhead.next; while (insertpost.val<post.val) { insertcur = Insertcur.next; Insertpost = Insertpost.next; } Cur.next = Post.next; Post.next = Insertpost; Insertcur.next = post; Post = Cur.next; } } return newhead.next; }
Leetcode insertion Sort List