7.划分链表

划分链表

题目在这里插入图片描述

解题思路

  • Step1:将小于x和大于等于x的部分分别用头和尾指针创建链表
  • Step2:将两个链表连接起来

代码实现及注释

class Solution {
        /**
         * Step1:将小于x和大于等于x的部分分别用头和尾指针创建链表
         * Step2:将两个链表连接起来
         */
        public static ListNode partition(ListNode head, int x) {
            ListNode lefthead = null, lefttail = null;//小于x部分的头节点和尾节点
            ListNode righthead = null,righttail = null;//小大于等于x部分的头节点和尾节点
            ListNode next = null;//用于记录head的下一个节点(当把head加入新链表时需要将其head.next = null,如果不记录下一个节点,则无法继续进行遍历
            while (head != null){
                next = head.next;//将next记录呢需要的下一个节点
                head.next = null;//将head与原来的链表断连
                if (head.val<x){
                    if (lefthead == null){
                        lefthead = head;
                        lefttail = head;
                    }else {
                       lefttail.next = head;
                       lefttail = head;
                    }
                }else {
                    if (righthead == null){
                        righthead = head;
                        righttail = head;
                    }else {
                        righttail.next = head;
                        righttail = head;
                    }
                }
                head = next;//将head移动到下一个节点
            }
            if (lefthead == null){//如果小于x的那部分链表为null
                return righthead;//返回大于等于x那部分链表的头节点
            }
            if (lefthead!=null){//如果小于x的那部分链表不为null
                lefttail.next = righthead;//将大于等于x那部分链表拼接到尾部
            }
            return lefthead;//返回链表头部
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值