Insertion Sort List leetcode
Insert sorting method to sort the linked list
For convenience, only one header node is defined.
Ideas:
Define the header node result to make result-> next = head, and then extract the values in the linked list one by one, before inserting it to a proper position, you must first disconnect the new linked list with only one element head at the beginning.
Let p = head-> next p traverse later and insert the value of p into the appropriate new linked list.
The Code is as follows:
/*** Definition for singly-linked list. * struct ListNode {* int val; * ListNode * next; * ListNode (int x): val (x), next (NULL ){}*}; */class Solution {public: ListNode * insertionSortList (ListNode * head) {if (head = NULL | head-> next = NULL) return head; listNode * result = new ListNode (0); result-> next = head; ListNode * pur, * p, * temp; // define the two pointers pur to point to the first one in the current linked list (the first one in the first order after sorting is inserted) temp records the previous node p of pur to traverse the old linked list p = head-> next; temp = result; pur = head; // pur is used to traverse the new linked list pur-> next = NULL; // disconnects the linked list while (p) // traverses the old linked list {ListNode * q = p-> next; // save p's next node p-> next = NULL; while (pur & pur-> val
Val) // Insert the values in the old linked list into the new linked list to {temp = pur; // temp records the previous node of pur, use pur = pur-> next;} p-> next = pur; // Insert the node p temp-> next = p; temp = result; // because the original value is changed in the preceding operation, temp and pur need to restore pur = temp-> next; p = q; // make p continue traversal} return result-> next ;}};