LeetCode_Insertion Sort List

Sort a linked list using insertion sort.

这道题简单,就是使用插入排序的方式对链表进行排序,主要就是链表的基本操作。

需要注意的几点:

每步插入操作存在一下三种情况:

//case 1:if position is head

//case 2:position is not pCurrent

//case 3:position  is between head and pCurrent

也就是说需要插入的位置(position)不同,可能导致操作也就不同,这一点与针对于数组的插入操作不同。

代码中描述的很清楚。

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if (head==NULL)
        {
            return NULL;
        }
        if (head->next==NULL)
        {
            return head;
        }

        //insert sort
        ListNode* pCurrent;
        ListNode* pPreCurrent;
        pPreCurrent=head;
        pCurrent=head->next;
        while (pCurrent!=NULL)
        {
            ListNode* pPreCompare=NULL;
            ListNode* pCompare=head;
            //find position
            while (pCompare!=pCurrent)
            {
                if (pCompare->val>pCurrent->val)
                {
                    break;
                }
                pPreCompare=pCompare;
                pCompare=pCompare->next;
            }

            //case 1:if position is head
            if (pCompare==head)
            {
               //cut the pCurrent
                pPreCurrent->next=pCurrent->next;

                //change head and insert
                pCurrent->next=head;
                head=pCurrent;

                //change next  pCurrent
                pCurrent=pPreCurrent->next;
            }
            else
            {
                //case 2:position is not pCurrent
                if (pCompare==pCurrent)
                {
                    //change pCurrent and pPreCurrent
                    pPreCurrent=pCurrent;
                    pCurrent=pCurrent->next;
                }
                else
                {
                    //case 3:position  is between head and pCurrent
                    //cut pCurrent
                    pPreCurrent->next=pCurrent->next;

                    //insert pCurrent to position
                    pCurrent->next=pCompare;
                    pPreCompare->next=pCurrent;

                    //change next pCurrent
                    pCurrent=pPreCurrent->next;
                }
            }
        }
        return head;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值