Insertion Sort List --leetcode
来源:程序员人生 发布时间:2014-12-22 08:51:18 阅读次数:3161次
思路:创建1辅助节点,作为生成链表的头结点(不含有效数据)。遍历原链表中每个节点,并将其插入到新链表的对应位置
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
ListNode *dump = new ListNode(0);
if(head == NULL || head->next == NULL)
return head;
ListNode *prev = dump;
ListNode *cur = head;
ListNode *tmp;
while(cur)
{
prev = dump;
while((prev->next != NULL)&&(prev->next->val < cur->val))//找到1点,在该点以后插入
prev= prev->next;
tmp = cur->next;
cur->next = prev->next;
prev->next = cur;
cur = tmp;
}
return dump->next;
}
};
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠