/**
* 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* temp=head; //外层移动指针
ListNode* temp2=head; //内层移动指针
ListNode* help; //辅助换位
ListNode* temps=head->next;
while(temps!=NULL){
temp=temps;
temps=temps->next;
cout<<"value "<<temp->val<<endl;
int x;
cin>>x;
while(temp2!=temp){
if(temp->val>temp2->val)
{
cout<<temp2->val<<endl;
if(temp->val<=temp2->next->val) //找到组织
{
help=temp2->next;
temp2->next=temp;
temp->next=help;
break;
}else{
temp2=temp2->next;
}
}else{ //根据前面的条件,遇到这种情况说明比第一个小,即头结点
temp->next=head;
head=temp;
break;
}
}
temp2=head;
//if(temp2==temp){} //比之前所有的元素都大 不需要移动
}
return head;
}
};
当前存在的问题是如果把最后一个指针拿走比如(4,3,2,1,前面排序后为 2,3,4)当开始判断1时,1比当前首结点值小,把1的尾指针指向2,这时就形成了一个环路,算法没办法终止。
就算不是拿走最后一个元素,如果中间的元素的下一个头部指向元素,那么内层循环while(temp!=temp2),永远无法满足,同样死循环。
可以没取出一个元素做检查时,先保留它的next指针,然后把它的next指针置为空。
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
//if(head==NULL) return head;
ListNode* temp=head; //外层移动指针
ListNode* temp2=head; //内层移动指针
ListNode* help; //辅助换位
ListNode* temps=head->next;
head->next=NULL;
//怎么处理最后一个指针移到头部后,循环的问题,单拿出来,或是计数
//每次取出一个元素,先保存它的后一个元素,再把它的后一个置为NULL
while(temps!=NULL){
temp=temps;
temps=temps->next;
temp->next=NULL;
// cout<<temp->val<<endl;
while(temp2!=NULL){
if(temp->val>temp2->val)
{
//cout<<temp2->val<<endl;
if(temp2->next==NULL){
temp2->next=temp;
break;
}
if(temp->val<=temp2->next->val ) //找到组织
{
help=temp2->next;
temp2->next=temp;
temp->next=help;
break;
}else{
temp2=temp2->next;
}
}else{ //根据前面的条件,遇到这种情况说明比第一个小,即头结点
temp->next=head;
head=temp;
// cout<<"head: "<<head->val<<endl;
break;
}
}
temp2=head;
//if(temp2==temp){} //比之前所有的元素都大 不需要移动
}
return head;
}
};