前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Insertion Sort List

Leetcode: Insertion Sort List

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 15:30:02
3100
发布2019-01-22 15:30:02
举报

题目:Sort a linked list using insertion sort. 即使用插入排序对链表进行排序。

思路分析: 插入排序思想见《排序(一):直接插入排序

C++参考代码:

/**
 * 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 nullptr;
        //previous记住当前节点的前一个节点(因为单链表进行插入操作的时候必须知道当前节点的前一个节点)
        ListNode *previous = head;
        //current节点是要往前面已经排好序的节点中进行插入的节点
        ListNode *current = head->next;
        while (current)
        {
            //small和big指针用于记录比current小和比current大的指针,small和big相邻
            ListNode *small = nullptr;
            ListNode *big = head;
            while (big->val < current->val)
            {
                small = big;
                big = big->next;
            }
            //如果big!=current说明current节点应该插入到small和big节点之间
            if (big != current)
            {
                previous->next = current->next;
                if (small) small->next = current;
                else head = current;
                current->next = big;
            }
            //如果big=current这时previous指向下一个节点就OK了
            else
            {
                previous = previous->next;
            }
            //最后current节点指向previous下一个节点即current向前走一步
            current = previous->next;
        }
        return head;
    }
};

Java参考代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null) return null;
        ListNode previous = head;
        ListNode current = head.next;
        while (current != null) {
            ListNode small = null;
            ListNode big = head;
            //找出介于current的big和small元素,big和small相邻
            while (big.val < current.val) {
                small = big;
                big = big.next;
            }
            //如果big!=current将current插入到small和big之间
            if (big != current) {
                previous.next = current.next;
                if (small != null) small.next = current;
                else head = current;
                current.next = big;
            } else {
                previous = previous.next;
            }
            current = previous.next;
        }
        return head;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年04月04日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档