描述
用插入排序對鏈表排序
樣例
Given 1->3->2->0->null, return 0->1->2->3->null
思路
先看下插入算法 百度-插入算法
這道題不難,理解插入算法就會寫了
創建一個新鏈表,從原鏈表的head結點開始,用插入算法將結點插入到新鏈表中
代碼實現(c++)
ListNode *insertionSortList(ListNode *head) {
ListNode *dummy = new ListNode(0);
while(head != NULL) {
ListNode *temp = dummy;
ListNode *next = head->next;
while(temp->next != NULL && temp->next->val < head->val) {
temp = temp->next;
}
head->next = temp->next;
temp->next = head;
head = next;
}
return dummy->next;
}