牛客网---CM11 链表分割 代码详解+哨兵位的比较


前言

独处未必孤独喜欢就是自由
本章的内容是牛客网随机一题的部分方法的解析


提示:以下是本篇文章正文内容,下面案例可供参考

CM11 链表分割

链接:

CM11 链表分割 link

方法一:尾插(带哨兵位)

1.1 思路:

把小于x的尾插第一个链表,大于x的尾插第二个链表,最后链接在一起

1.2 代码:

class Partition {
    
    
public:
    ListNode* partition(ListNode* pHead, int x) 
    {
    
    
        struct ListNode* lesshead,*lesstail,*greaterhead,*greatertail;
        lesshead=lesstail=(struct ListNode*)malloc(sizeof(struct ListNode));
        greaterhead=greatertail=(struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode* cur=pHead;
        while(cur)
        {
    
    
            if(cur->val<x)
            {
    
    
                lesstail->next=cur;
                lesstail=lesstail->next;
            }
            else 
            {
    
    
                greatertail->next=cur;
                greatertail=greatertail->next;
            }
            cur=cur->next;
        }
        lesstail->next=greaterhead->next;
        greatertail->next=NULL;
        pHead=lesshead->next;
        free(lesshead);
        free(greaterhead);
        return pHead;
    }
};

1.3 流程图

在这里插入图片描述

1.4 注意点

  • 易错点一: lesstail->next=greaterhead->next
    这是带哨兵位的链表,所以应该是 lesstail->next=greaterhead->next;而不应该是 lesstail=greaterhead;
  • 易错点二:末尾要置空否则造成循环链表greatertail->next=NULL;
    一定要加上greatertail->next=NULL;不然当出现一个链表中既有大于x又有小于x的时候(例如上述流程图7的next指向的还是2如果不置空就会造成循环)
    在这里插入图片描述

方法二:尾插(不带哨兵位)

2.1代码:

class Partition {
    
    
public:
    ListNode* partition(ListNode* pHead, int x) 
    {
    
    
        struct ListNode* lesshead,*lesstail,*greaterhead,*greatertail;
        lesshead=lesstail=NULL;
        greaterhead=greatertail=NULL;
        struct ListNode* cur=pHead;
        while(cur)
        {
    
    
            if(cur->val<x)
            {
    
    
                if(lesstail==NULL)
                {
    
    
                    lesstail=lesshead=cur;
                }
                else 
                {
    
    
                    lesstail->next=cur;
                    lesstail=lesstail->next;
                }
            }
            else 
            {
    
    
                if(greatertail==NULL)
                {
    
    
                    greatertail=greaterhead=cur;
                }
                else 
                {
    
    
                    greatertail->next=cur;
                    greatertail=greatertail->next;
                }
            }
            cur=cur->next;
        }
        if(lesstail==NULL)
        {
    
    
            return greaterhead;
        }
        else 
        {
    
    
             lesstail->next=greaterhead;
        }       
        if(greatertail!=NULL)
        {
    
    
            greatertail->next=NULL;
        }
        pHead=lesshead;
        return pHead;
    }
};

对比:

对比方法一和方法二,很明显带哨兵位可以优化代码减少判断的次数不用考虑头节点是否为空的情况


总结

Ending,今天的内容就到此结束啦,如果后续想了解更多,就请关注我吧,一键三连,还有许多种方法没有写出希望各位佬补充哦~

猜你喜欢

转载自blog.csdn.net/ljq_up/article/details/130473488