面试题 02.04. 分割链表

面试题 02.04. 分割链表

编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x,x 只需出现在小于 x 的元素之后(如下所示)。分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。

示例:

输入: head = 3->5->8->5->10->2->1, x = 5
输出: 3->1->2->10->5->5->8

方法1:双指针/交换值

/**
 * 类似荷兰国旗的想法,prev指针指向小于x的 ,cur游走进行判断
 *
 * @param head
 * @param x
 * @return
 */
public ListNode partition(ListNode head, int x) {
    ListNode prev = head, cur = head;
    while (cur != null) {
        if (cur.val < x) {//当前节点的值需要进行交换
            int t = prev.val;//先存下来prev的val
            prev.val = cur.val;//swap
            cur.val = t;
            prev = prev.next;//prev跳到下一个指针
        }
        cur = cur.next;//cur一直游走
    }
    return head;
}

方法2:双指针/两个指针遍历

public ListNode partition(ListNode head, int x) {
            ListNode left = new ListNode(-1), right = new ListNode(-1);
            ListNode leftDummy = left, rightDummy = right;
            while (head != null) {
                if (head.val < x) {
                    left.next = head;
                    left = left.next;
                } else {
                    right.next = head;
                    right = right.next;
                }
                head = head.next;
            }
            //比如[1,4,3,2,5,2] x=3这个例子, leftDummy->1->2->2 如果没有断开操作,
            // 那 rightDummy->4->3->5->2就不正确了,因为原链表中5->2,没有断开,导致后面拼接操作会把这个链表成环
            right.next = null;
            left.next = rightDummy.next;
            return leftDummy.next;
        }

方法3:头插法

在这里插入图片描述

    public ListNode partition(ListNode head, int x) {
            if (head == null) return null;
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode prev = head;
            head = head.next;
            while (head != null) {
                if (head.val < x) {
                    prev.next = head.next;
                    head.next = dummy.next;//当前节点的指向 dummy节点的下一个节点
                    dummy.next = head;//当前要移动的点
                    head = prev.next;
                } else {
                    prev = prev.next;//顺序移动
                    head = head.next;//顺序移动
                }
            }
            return dummy.next;
        }
方法4:头插法
  • 极少的变量
public ListNode partition(ListNode head, int x) {
    if (head == null) return null;
    ListNode cur = head;
    while (cur.next != null) {
        if (cur.next.val < x) {
            ListNode t = cur.next;
            cur.next = cur.next.next;
            t.next = head;
            head = t;
        } else {
            cur = cur.next;
        }
    }
    return head;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值