[LeedCode OJ] #147 Insertion Sort List,
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Link: https://leetcode.com/problems/insertion-sort-list/
Question:
Given a linked list, insert sorting is required to return a sorted linked list.
Ideas:
Create a new linked list. sort by insertion. Find the position of the new node to be inserted in each cycle.
/** * 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==nullptr || head->next==nullptr)return head;ListNode *newlist = new ListNode(0);ListNode *cur = head;while(cur){ListNode *ptr = newlist;ListNode *pnext = cur->next;while(ptr && ptr->next && ptr->next->val<cur->val){ptr = ptr->next;}cur->next = ptr->next;ptr->next = cur;cur = pnext;}return newlist->next;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source