链表插入排序
问题描述:用插入排序对链表排序 如给定1->3->2->0->NULL;返回0->1->2->3->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 *dummy=new ListNode(0);
while(head!=NULL){
ListNode *node=dummy;
while(node->next!=NULL&&node->next->val<head->val)
{
node=node->next;
}
ListNode *temp=head->next;
head->next=node->next;
node->next=head;
head=temp;
}
return dummy->next;
}
};
public:
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
ListNode *insertionSortList(ListNode *head) {
// write your code here
ListNode *dummy=new ListNode(0);
while(head!=NULL){
ListNode *node=dummy;
while(node->next!=NULL&&node->next->val<head->val)
{
node=node->next;
}
ListNode *temp=head->next;
head->next=node->next;
node->next=head;
head=temp;
}
return dummy->next;
}
};