问题描述:
用插入排序对链表排序。
样例:
Given 1->3->2->0->null
, return 0->1->2->3->null.
思路:
新建一个链表,按从小到大顺序排列,从原列表
代码:
/**
* 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
if (head->next== NULL || head== NULL) return head;
ListNode *q, *p, *first, *r;
p= head;
first= new ListNode(0);
while (p!= NULL) {
q= first;
while (q->next!= NULL && q->next->val< r->val) {
q= q->next;
}
r=p->next;
p->next= q->next;
q->next= p;
p= r;
}
return first->next;
}
};
感想:
链表排序用到了链表的插入操作,插入排序跟数组相比操作当对简单一点不需要移动数据,只要在当前位置插入就可以了,但是在那个位置插需要思考一下。每次用一个迭代的指针的下一个数据域跟要插入的比较大小,这样就可以找到当前指针数据域小于插入的数据,而后面的那个是大于要插入的数据的。