Insertion Sort List leetcode

Source: Internet
Author: User

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 ;}};
 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.