码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ - Insertion Sort List

时间:2014-05-16 05:47:08      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

题目:

  Sort a linked list using insertion sort.

解题思路:

  假设 list[1..i]是排好序的,找到第i+1个元素应该插入的位置及其前驱,然后将其插入。

代码:

  

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;
        }
        
        /*找到最小的元素作为表头*/
        ListNode *p_tmp = head;
        int min_val = head->val;
        
        ListNode *p_current = head->next;
        while (p_current != NULL) {
            if (p_current->val < min_val) {
                p_tmp = p_current;
                min_val = p_current->val;
            }
            p_current = p_current->next;
        }
        p_tmp->val = head->val;
        head->val = min_val;
        
        ////////////////////////////////////////////////////////
        p_current = head->next;
        while (p_current != NULL){
            ListNode *p_next = p_current->next;

            ListNode *p_pos = head; //找插入位置
            while (p_pos != p_current && p_pos->next->val <= p_current->val) p_pos = p_pos->next;

            ListNode *p_pre = head;  // 找前驱
            while (p_pre->next != p_current) p_pre = p_pre->next;

            if (p_pos != p_current) {
                p_pre->next = p_current->next;
                p_current->next = p_pos->next;
                p_pos->next = p_current;
            }

            p_current = p_next;
        }
        return head;
    }
};
bubuko.com,布布扣

 

LeetCode OJ - Insertion Sort List,布布扣,bubuko.com

LeetCode OJ - Insertion Sort List

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/dongguangqing/p/3726305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!