單鏈表元素排序
Sort a linked list using insertion sort. 對鏈表中的元素進行插入排序。
C++中使用指針的時候,一定要注意在使用指針之前要對其進行初始化,即不能讓指針指向任何地方。指針一定要指向一個確定的地方。初始化如下:
ListNode *p=new ListNode; //申請一個結點p。程序會給他分配內存。
代碼塊
/**
* 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) {
ListNode *first=head; //用來遍歷原列表
if(first==NULL)return head;
ListNode *r=new ListNode(0); //用來遍歷現已排序好的列表
ListNode *pre=new ListNode(0); //用來保存插入結點時的前面一個結點 –頭插法
ListNode *lis=new ListNode(0); //已排序好的列表
r->val=first->val;
r->next=NULL;
head=r;
while(first->next!=NULL){
int data=first->next->val; //插入數
pre=r;
bool flag=false;
head=r;
while(r!=NULL&&data>=r->val){ //當插入的數比後面的數還要小時 --從小到大
pre=r; //保存前面結點
r=r->next;
flag=true;
}
ListNode *temp=new ListNode(0);
temp->val=data;
if(flag==true){
temp->next=pre->next; //插入結點r
pre->next=temp;
}else{
temp->next=pre;
head=temp;
}
first=first->next;
r=head;
}
return head;
}
};