【LeetCode】147. 对链表进行插入排序

插入排序算法:

  1. 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
  2. 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
  3. 重复直到所有输入数据插入完为止。

方法1:严格按照算法说明,在原始列表中进行操作,利用4个链表指针分别表示当前元素位置,当前元素前一个元素位置,从头结点开始第一个比当前元素大的元素以及该元素前一个元素的位置。

ListNode* Solution::insertionSortList(ListNode *phead)
{
    /*pcurrent -> p2 at init*/
    ListNode *pcurrent;
    ListNode *pleft;
    ListNode *prepleft,*ptemp,*precurrent;
    if((phead->next == NULL)||(phead->next->next == NULL))
    {
        cout<<"tail length = 0/1, no need to insert";
        return phead;
    }
    pcurrent = phead->next->next;
    precurrent = phead->next;
    while(pcurrent != NULL)
    {
        /*pleft -> p1 every loop start*/
        prepleft = phead;
        pleft = phead->next;
        while(pleft != pcurrent)
        {
            if(pleft->val > pcurrent->val)
            {
                prepleft->next = pcurrent;
                ptemp = pcurrent->next;
                pcurrent->next = pleft;
                precurrent->next = ptemp;
                /*pcurrent position is changed,should be repalced by pleft*/
                pcurrent = pleft;
                break;
            }
            else
            {
                prepleft = pleft;
                pleft = pleft->next;
            }
        }
        precurrent = pcurrent;
        pcurrent = pcurrent->next;
    }
    return phead;
}

此方法提交在xcode环境验证ok,但提交LeetCode显示超时。

方法2:不在原链表中进行操作,新建一个链表头对原链表中的元素进行插入排序

ListNode* Solution::NewinsertionSortList(ListNode *phead)
{
    if((phead == NULL)||(phead->next == NULL))
    {
        return phead;
    }
    /*new head to insert*/
    ListNode *Newhead = new ListNode(0);
    ListNode *pcurrent = phead;
    while(pcurrent)
    {
        ListNode *pnext = pcurrent->next;
        phead = Newhead;
        while((phead->next != NULL) && (phead->next->val < pcurrent->val))
        {
            phead = phead->next;
        }
        /*find pisition to insert*/
        pcurrent->next = phead->next;
        phead->next = pcurrent;
        pcurrent = pnext;
    }
    return Newhead->next;
}

猜你喜欢

转载自blog.csdn.net/syc233588377/article/details/85060250