原题网址:http://www.lintcode.com/zh-cn/problem/insertion-sort-list/#
用插入排序对链表排序
您在真实的面试中是否遇到过这个题?
Yes
样例
Given 1->3->2->0->null
, return 0->1->2->3->null
标签
思路:不清楚插入排序是个什么排序,我的想法是复制原链表的值重建一新个链表,对每一个新节点,判断其值与新链表头结点的关系,小于则插入头节点处;
大于就继续向下判断,找到插入位置,这里注意应保存头结点以便下次插入。
最后返回新链表头结点指针。
AC代码:
/** * Definition of singly-linked-list: * 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==NULL) { return head; } ListNode *p=new ListNode(head->val);//新链表头结点; while(head->next!=NULL) { ListNode *node=new ListNode(head->next->val); if (node->val>p->val) { ListNode *tm=p;//保存头结点; while(p->next!=NULL&&node->val>p->next->val) { p=p->next; } node->next=p->next; p->next=node; p=tm; } else { node->next=p; p=node; } head=head->next; } return p; } };
看了下网上代码,感觉自己没理解错,就是代码可以进一步优化……参考:https://blog.csdn.net/yaomf/article/details/68229742
其他 冒泡法