首页 > 其他 > 详细

[LeetCode] Insertion Sort List

时间:2014-03-14 19:08:01      阅读:411      评论:0      收藏:0      [点我收藏+]

Sort a linked list using insertion sort.

Solution:

新建链表,逐个插入即可~

bubuko.com,布布扣
/**
 * 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) {
        if(head == NULL || head -> next == NULL) 
            return head; //0 and 1 nodes return itself
        
        ListNode *sortedHead = new ListNode(head -> val), *srcNode = head -> next;
        while(srcNode != NULL)
        {
            ListNode *preNode = NULL, *curNode = sortedHead;
             while(curNode != NULL)
            {
                if(curNode -> val < srcNode -> val)
                 {
                     preNode = curNode;
                        curNode = curNode -> next;
                }
                else
                    break;
            }
            if(preNode != NULL)
            {
                preNode -> next = new ListNode(srcNode -> val);
                preNode -> next -> next = curNode;
            }
            else
            {
                ListNode *tmp = sortedHead;
                sortedHead = new ListNode(srcNode -> val);
                sortedHead -> next = tmp;
            }
            srcNode = srcNode -> next;
        }
        
        return sortedHead;
    }
};
bubuko.com,布布扣

[LeetCode] Insertion Sort List,布布扣,bubuko.com

[LeetCode] Insertion Sort List

原文:http://www.cnblogs.com/changchengxiao/p/3598185.html

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