題意:
給定一個鏈表,要求使用插入排序返回一個排好序的鏈表
思路:
建立新的鏈表,按照插入排序的特點,每次循環新鏈表找到新結點將要插入的位置
/** * 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->valval) { ptr = ptr->next; } cur->next = ptr->next; ptr->next = cur; cur = pnext; } return newlist->next; } };