The principle is very simple, that is, insert sorting. It is only because of the nature of the linked list that you must search for the inserted position from the front to the back. However, it is easy to have various bugs, and it is difficult to implement bug-free once.
Package Level4; import Utility. listNode;/*** Insertion Sort List *** Sort a linked list using insertion sort. **/public class S135 {public static void main (String [] args) {ListNode head = new ListNode (4); ListNode n2 = new ListNode (2 ); listNode n3 = new ListNode (1); ListNode n4 = new ListNode (3); ListNode n5 = new ListNode (1); head. next = n2; n2.next = n3; n3.next = n4; // n4.next = n5; // Li StNode ret = insertionSortList (head); // ret. print (); int [] list = {-84,142, 41,-17,-71,170,186,183,-21,-81,112,-39,-6, 41,111, 150,149, 69, 97,-30,164,153,-44,-92,180, 81,147,109, 14,178,105,-21, 16,123,-192,-96,106,131, 64,189,-22,105,104,-34,-56,-,-91,-34,-56, 22,-31,-85,184, 118,152, 31,161,-,-, 22, 104,-85,160,120,-31,144,115}; // int [] list = {,}; // int [] list = }; listNode dum = ListNode. create (list); // dum. print (); ListNode ret = insertionSortList (dum); ret. print ();} public static ListNode insertionSortList (ListNode head) {if (head = null | head. next = null) {return head;} ListNode p = head; // two pointers before and after ListNode q = head. next; while (p! = Null & q! = Null) {if (p. val <= q. val) {// incremental order, no need to switch, continue to search for p = q; q = q. next;} else {// out of order! ListNode h = head; if (head. val> = q. val) {// when the q element is smaller than the head element, ListNode qnext = q. next; p. next = qnext; q. next = head; head = q; // update the linked list header q = qnext; // update the q position so that q can continue searching} else {while (h. val <= q. val & h. next. val <= q. val) {// start from the head and find out where the q element is suitable. Pay attention to equal elements! H = h. next;} if (h. val <= q. val & q. val <= h. next. val) {// Insert the q element into the appropriate location ListNode qnext = q. next; p. next = qnext; q. next = h. next; h. next = q; q = qnext; // update the q position, so that q can continue to search. }}} return head ;}}