从一个链表中分成两个链表再将他们连到一起需要注意的点

问题描述


8d00adc36ec6b14a6001efb47cb14390.png

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head ListNode类
 * @param x int整型
 * @return ListNode类
 */
struct ListNode* partition(struct ListNode* head, int x ) {
    // write code here

    struct ListNode* smallerhead = NULL, *smallertail = NULL;
    struct ListNode* biggerhead = NULL, *biggertail = NULL;
    struct ListNode* pt = head;

    if(head==NULL){
        return NULL;
    }

    while (pt) {
        if (pt->val < x ) {
            if (smallerhead == NULL) {
                smallerhead =smallertail= pt;
            }
            else{
                smallertail->next = pt;
                smallertail=pt;
            }
     

        } else {
            if (biggerhead == NULL) {
                biggerhead=biggertail = pt;

            }
            else{
                biggertail->next = pt;
                biggertail=pt;

            }

        }
        pt = pt->next;
    }
    if(smallertail){
        smallertail->next=biggerhead;
        return smallerhead;


    }
    else{
        return biggerhead;
    }
  
}

以上是原先的代码,提交后发现

这边死循环了,而且发现5 2 4 3 5重复出现


 

原因分析:

将原数据重新走一遍后,发现这个5还跟2链接着,所以最后输出时就会死循环,类似下图这样


 

解决方案:

所以这边想到了在最后把biggertail->next 给置空,这样就不会牵连到2了

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值