首页 > 其他 > 详细

Insertion Sort List --leetcode

时间:2014-11-30 09:15:40      阅读:224      评论:0      收藏:0      [点我收藏+]

思路:创建一辅助节点,作为生成链表的头结点(不含有效数据)。遍历原链表中每一个节点,并将其插入到新链表的对应位置

/**
 * 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))//找到一点,在该点之后插入
                prev= prev->next;
            tmp = cur->next;
            cur->next = prev->next;
            prev->next = cur;
            cur = tmp;
        }
        return dump->next;
    }
};


Insertion Sort List --leetcode

原文:http://blog.csdn.net/youxin2012/article/details/41620279

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!