描述
用插入排序对链表排序
样例
Given 1->3->2->0->null, return 0->1->2->3->null
思考
- 非插入排序
- 插入排序
代码
// By Lentitude
/**
* 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
/**
* 先计算节点的总数
* 进行遍
*/
ListNode *temp = head, *l1;
int numOfList = 0; // 节点数目
while (temp){
++numOfList;
temp = temp->next;
}
for (int i = 0; i != numOfList; ++i){
for (l1 = head; l1->next != NULL; l1 = l1->next){
if(l1->val > l1->next->val ){
swap(l1->val, l1->next->val);
}
}
}
return head;
}
};
// By Lentitude