您的位置:首页 > 其它

LintCode 链表插入排序

2017-03-21 22:41 267 查看
题目描述:

用插入排序对链表排序

样例

Given 1->3->2->0->null, return 0->1->2->3->null。

思路分析:

感觉是链表的进阶题。

写完这道题,后面题都很简单啦。

ac代码:

/**
* 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 *r,*dummy;
r=new ListNode(0);
//dummy=head;   //记录原链表的头节点。
while(head!=NULL)
{
ListNode *node=r;  //遍历 r链表。
while(node->next!=NULL && node->next->val<head->val)
{
node=node->next;
}
ListNode *temp=head->next; //先保存下来 head 的下一个节点。
head->next=node->next;
node->next=head;
head=temp;
}
return r->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表