Sort a linked list using insertion sort.
Question]
Sort a linked list by insert sort.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
[Idea]
Basic questions. The difficulty lies in understanding the linked list knot, because next is both the attribute of the current node and the next node.
Add a new header newhead before the head, because a node may need to be inserted before the head during insertion sorting. In this case, the newhead is needed.
[Java code]
Public class solution {public listnode insertionsortlist (listnode head) {If (Head = NULL | head. next = NULL) return head; // It is easy for beginners to ignore this line of listnode newhead = new listnode (0); newhead. next = head; // Add a new header before the head newhead listnode P = head. next; // traverse head starting from the second node. next = NULL; // currently, the sorted linked list only has two nodes: newhead and head. The advantage of this is that if the nodes inserted after the head are all before the head, it can be ensured that the end of the sorted linked list points to null while (P! = NULL) {// use P to traverse the listnode cur = P; P = P. next; cur. next = NULL; // if this node needs to find the end of the linked list, this ensures that the end of the linked list points to null listnode node = newhead. next; listnode pre = newhead; while (node! = NULL) {// use node to traverse the sorted linked list. Pre indicates that the previous if (cur. val <node. val) {// insert cur pre. next = cur; cur. next = node; break;} else {// It is not inserted yet, continue backward, and update pre = node; node = node at the same time. next;} If (node = NULL) {// If the inserted position is pre at the end of the linked list. next = cur ;}}return newhead. next ;}}
Let's not talk about it much. Just clear the idea and identify the variable and the item in the linked list. You may want to start all over again in a chaotic situation.
[Leetcode] insertion sort list