Article directory
LeetCode - 147. Insertion Sort on Linked Lists
Topic Analysis
Ask us to sort the linked list and specify the insertion sorting algorithm.
Refer to this article Common Sort - Common Sorts and Uncommon Sorts
Problem solving ideas
Ideas: Create a puppet head node newHead and make its linked list a head (newH.next = head).
Define a reference pointer lastSorted = head; and cur = head.val;
cur is the data to be inserted and sorted, and lastSorted is used to find nodes with a value greater than cur.val.
There may be more than one data that needs to be inserted and sorted, so loop a loop.
Then, lastSorted is used to find nodes larger than the cur.val value.
Now that the successor node is found, then we only need to find the predecessor node [val value is smaller than cur]. So, we only need to define a node to refer to prev, starting from the puppet, looking for the precursor node of cur.
Use the predecessor node prev and the successor node lastSorted to perform the insertion operation.
At this point, the question is not over! Finally, return to newHead.next and it's OK.
code show as below:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null){
return head;
}
ListNode newHead = new ListNode();
newHead.next = head;
ListNode lastSorted = head;
ListNode cur = head.next;
while(cur != null){
if(lastSorted.val <= cur.val){
lastSorted = lastSorted.next;
}else{
ListNode prev = newHead;
while(prev.next.val <= cur.val){
prev = prev.next;
}
lastSorted.next = cur.next;
cur.next = prev.next;
prev.next = cur;
}
cur = lastSorted.next;
}
return newHead.next;
}
}
code details
If you are interested, you can click
All of LeetCode's linked list questions are here , except for VIP and Hash questions, almost all of them are in it. The problems of binary tree, sorting, heap, stack and queue are being improved step by step.