单链表元素排序
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;
}
};