链表专题之Partition List leetcode(86)

给一个链表和一个数值x,要求对链表进行划分,使得小于x的节点位于大于等于值为x的节点的左侧,保持其他节点的相对位置

Given 1->4->3->2->5->2 and x = 3,

return 1->2->2->4->3->5.

思想:构造两个链表,然后改变指针的指向,注意极端情形

ListNode* partition(ListNode* head, int x) {
        
        if(!head)
            return head;
        ListNode* tmpHead1 = NULL;    //小于x的左侧链表头结点
        ListNode* tmpHead2 = NULL;     //不小于x的右侧链表头结点
        ListNode* tmp1 = NULL;    //左侧链表的尾节点
        ListNode* tmp2 = NULL;     //右侧链表的尾节点
        
        ListNode* p = head;
        
        while(p)
        {
            if(p->val<x)
            {
                if(tmpHead1 == NULL)    //提交的代码汇总,最快的6ms,我的花了10ms,这个地方判断太多次了!
                {
                    tmpHead1 = p;
                }
                else
                {
                    tmp1->next = p;

                }

                tmp1 = p;   

            }
            else
            {
                if(tmpHead2 == NULL)
                {
                    tmpHead2 = p;
                }
                 else
                {
                    tmp2->next = p;
                }
                tmp2 = p;
            }
            
            p = p->next;
        }
        if(tmp2)    //考虑存在右侧链表的情形,由于是对原来的链表操作,因此需要设置为空
        {
             tmp2->next = NULL;
        }
       
        if(!tmp1)    //检查左侧链表的尾节点是否为空,若为空则返回右侧链表
        {
            return tmpHead2;
        }
        else    //否则将两个链表合并起来
        {
            tmp1->next = tmpHead2;
        }
        
        
        return tmpHead1;
        
        
    }

猜你喜欢

转载自blog.csdn.net/u012260341/article/details/79533033
今日推荐