题目:
Sort a linked list using insertion sort.
思路:使用插入算法为链表进行排序,这里选择的插入,对于每一个待插入的节点,需要记录此节点的前面和后面的节点,从头开始遍历拍好序的链表,如果找到一个元素合适的插入位置,我们需要插入到此节点之前,但是为了方便,我们插入到此节点的后面,然后交换两个节点的值,同时需要注意的是,由于是此节点是插入到某一个节点之后,那么如果位置节点和待插入节点之前的节点一样需要特殊考虑。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef struct list_node List;
struct list_node
{
struct list_node* next;
int value;
};
void print_list(List* list)
{
List* tmp=list;
while(tmp != NULL)
{
cout<<tmp->value<<endl;
tmp = tmp->next;
}
}
/*
初始化List 将从1~n的数字插入到链表中
*/
void Init_List(List*& head,int* array,int n)
{
head = NULL;
List* tmp;
List* record;
for(int i=1;i<=n;i++)
{
tmp = new List;
tmp->next = NULL;
tmp->value = array[i-1];
if(head == NULL)
{
head = tmp;
record = head;
}
else
{
record->next = tmp;
record = tmp;
}
}
}
int Len_list(List* list)
{
if(list == NULL)
return 0;
else
return Len_list(list->next)+1;
}
void InsertSortList(List*& list)
{
if(list == NULL || list->next == NULL)
return;
List* head = list;
List* cur = list->next;
List* pre = list;
List* tmp;
while(cur != NULL)
{
tmp = cur->next;
for(head = list;head != cur;head = head->next)
{
if(cur->value <= head->value)
{
if(head != pre)
{
cur->next = head->next;
head->next = cur;
pre->next = tmp;
swap(head->value,cur->value);
cur = tmp;
}
else
{
swap(head->value,cur->value);
pre = cur;
cur = tmp;
}
break;
}
}
if(head == cur)
{
pre = cur;
cur = tmp;
}
}
}
int main()
{
int array[]={5,1,2,7,8,4,3,6,10,9};
List* list;
Init_List(list,array,sizeof(array)/sizeof(int));
InsertSortList(list);
print_list(list);
return 0;
}
ps:其实对于链表的操作,如果借助于辅助指针的话,很多问题都会变得简单,比如在最初我们使用一个伪指针起串连作用,,我们每次插入节点时,都是插入cur->next节点,而且每次插入的时候都从伪指针head开始遍历,这么我们就解决了两个问题,第一个问题是直接插入到目标位置,不用交换,第二个问题是我们解决了cur->next指针指向的问题,因为我们插入的是cur->next,如果cur->next被置换到前面的位置之后, list* temp = cur->next (其实我们刚才插入的就是temp这个节点) 然后cur->next= cur->next->next即可。