LeetCode自我總結(對連結串列進行插入排序)
對連結串列進行插入排序。
插入排序的動畫演示如上。從第一個元素開始,該連結串列可以被認為已經部分排序(用黑色表示)。
每次迭代時,從輸入資料中移除一個元素(用紅色表示),並原地將其插入到已排好序的連結串列中。
插入排序演算法:
- 插入排序是迭代的,每次只移動一個元素,直到所有元素可以形成一個有序的輸出列表。
- 每次迭代中,插入排序只從輸入資料中移除一個待排序的元素,找到它在序列中適當的位置,並將其插入。
- 重複直到所有輸入資料插入完為止。
示例 1:
輸入: 4->2->1->3 輸出: 1->2->3->4
示例 2:
輸入: -1->5->3->4->0 輸出: -1->0->3->4->5
class Solution {
public:
ListNode* insertionSortList(ListNode* head)
{
if(!head||!head->next)
{
return head;
}
ListNode* newhead=new ListNode(-1);//常用技巧,新建頭結點
newhead->next=head;
ListNode* pre=newhead;//這個指標的目的是每一次找插入的位置都要從頭結點開始遍歷
ListNode* current=head;//這個指標是當前我們需要操作的節點前一個節點
while(current)
{
if(current->next!=NULL&¤t->val>current->next->val)//若當前節點大於下一個節點,需要找位置移動插入了
{
while(pre->next!=NULL&&pre->next->val<current->next->val)
{
pre=pre->next; //遍歷找到要插入的位置
}
ListNode* temp=pre->next; //為什麼不是current呢,因為不一定要插入的位置正好是current的前面,但一定插入在pre的後面
pre->next=current->next;
current->next=current->next->next;
pre->next->next=temp;
pre=newhead;
}
else
{
current=current->next;
}
}
return newhead->next;
}
};