LeetCode 147. Insertion Sort List

本文提供了两种实现LeetCode 147题“插入排序链表”的解决方案。第一种方法较为直观但效率较低;第二种方法借鉴他人思路,代码更为简洁高效。通过对两种方法的对比,可以学习到如何优化链表操作。

LeetCode 147. Insertion Sort List

Solution1:我的答案
有点笨,有点慢

/**
 * 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) return NULL;
        if (!head->next) return head;
        ListNode* new_head = new ListNode(-1), *cur = head;
        while (cur) {
            ListNode *temp = cur->next;
            cur->next = NULL;
            my_insert(new_head, cur);
            cur = temp;
        }
        return new_head->next;
    }

    void my_insert (ListNode* &new_head, ListNode* &des) {
        if (!new_head->next || des->val <= new_head->next->val) {
            ListNode *temp = new_head->next;
            new_head->next = des;
            des->next = temp;
            return;
        } else {
            ListNode* cur = new_head->next;
            while (cur->next) {
                if (des->val >= cur->val && des->val <= cur->next->val) {
                    des->next = cur->next;
                    cur->next = des;
                    return;
                }
                else
                    cur = cur->next;
            }
            cur->next = des;
            return;
        }
    }
};

Solution2:
参考网址:http://www.cnblogs.com/grandyang/p/4250107.html

/**
 * 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 *dummy = new ListNode(-1), *cur = dummy;
        while (head) {
            ListNode *t = head->next;//暂时保存头结点的下一个位置
            cur = dummy;
            while (cur->next && cur->next->val <= head->val) {
                cur = cur->next;
            }
            head->next = cur->next;
            cur->next = head;
            head = t;
        }
        return dummy->next;
    }
};

要反思为啥别人的代码写的如此简洁~~~

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值