LeetCode_Insertion Sort List

来源:互联网 发布:mac如何下载qq游戏 编辑:程序博客网 时间:2024/05/17 06:08

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
原创粉丝点击