现在的位置: 首页 > 综合 > 正文

Leetcode: Sort List – 插入

2014年10月09日 ⁄ 综合 ⁄ 共 579字 ⁄ 字号 评论关闭

Sort a linked list using insertion sort.

还是插入排序简单呀。

/**
 * 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 *cur = head->next;
        head->next = NULL;
        ListNode *prev = NULL;
        ListNode *target = NULL;
        ListNode *tmp = NULL;
        while (cur != NULL) {
            prev = NULL;
            target = head;
            while (target != NULL && target->val <= cur->val) {
                prev = target;
                target = target->next;
            }
            if (prev == NULL) {
                head = cur;
            }
            else {
                prev->next = cur;
            }
            tmp = cur->next;
            cur->next = target;
            cur = tmp;
        }
        
        return head;
    }
};

抱歉!评论已关闭.