问题描述:用插入排序对链表排序
样例:Given 1->3->2->0->null, return 0->1->2->3->null
实现思路:本题要用插入排序对链表进行排序,首先考虑特殊情况,当链表是空的时候,直接返回0;若不是,就申请一个新的链表,首先将给定链表的第一个节点插进去,然后遍历它后面的节点,若比它小,则插在前面,否则,插在后面。
实现代码:
* 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) {
ListNode *dummy=new ListNode(0);
if(head==NULL)
return 0;
while(head!=NULL){
ListNode *pre=dummy;
while(pre->next!=NULL&&pre->next->val<head->val)
{pre=pre->next;}
ListNode *temp=head->next;
head->next=pre->next;
pre->next=head;
head=temp;
}
return dummy->next;// write your code here
}
};
做题感想:这个题让我就感觉挺绕的,老师上课还讲了一遍,当时感觉听明白了,但是自己写的时候又绕不过来了。