链表插入排序
题目描述:用插入排序法对链表进行排序
given 1->3->2->0->NULL, return 0->1->2->3->NULL
算法描述:
算法一:将题目中给出的链表数据结构转换为C++标准库中的标准list数据结构,调用c++标准库中的list算法进行排序即可完成
算法二:将题目中给出的链表数据结构转换为vrector,对vector进行插入排序,插入排序的算法如下所示:
vector<int> insertSort(vector<int> a, int length)
{
int key,i;
for(int j = 1;j<length;j++)
{
key = a[j];
i = j;
while(i>0 && a[i-1] > key)
{
a[i] = a[i-1];
i = i-1;
}
a[i] = key;
}
return a;
}
插入排序的整体思想类似于玩扑克牌游戏摸牌阶段整理扑克牌顺序的思想。再对排序好的vector创建为list。创建list的代码如下:
ListNode* createList(vector<int>a, int length)
{
ListNode * head, *tail, *mid;
head = tail = NULL;
int i = 0;
while (i < length)
{
mid = new ListNode(-1);
mid->val = a[i];
mid->next = NULL;
if (head == NULL)
{
head = mid;
}
else
{
tail->next = mid;
}
tail = mid;
i++;
}
return head;
}
则解决该问题的整体代码如下:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
ListNode *insertionSortList(ListNode *head)
{
// write your code here
//step one: List 2 vector
vector<int> raw_data;
vector<int> mid_data;
ListNode* result;
while(head != NULL)
{
raw_data.push_back(head->val);
head = head ->next;
}
//step two: sorting
mid_data = insertSort(raw_data,raw_data.size());
//step three: vector 2 list
result = createList(mid_data,raw_data.size());
return result;
}
vector<int> insertSort(vector<int> a, int length)
{
int key,i;
for(int j = 1;j<length;j++)
{
key = a[j];
i = j;
while(i>0 && a[i-1] > key)
{
a[i] = a[i-1];
i = i-1;
}
a[i] = key;
}
return a;
}
ListNode* createList(vector<int>a, int length)
{
ListNode * head, *tail, *mid;
head = tail = NULL;
int i = 0;
while (i < length)
{
mid = new ListNode(-1);
mid->val = a[i];
mid->next = NULL;
if (head == NULL)
{
head = mid;
}
else
{
tail->next = mid;
}
tail = mid;
i++;
}
return head;
}
};