Partition List

本文介绍了一种链表处理算法,使用两个哑节点创建临时链表来分别存储小于阈值x的节点和大于等于x的节点,最后将两部分链接起来形成有序链表。这种方法可以有效地解决链表的分区问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这种链表的思路一定要掌握:

两个dummy node各开一条临时链表,最后在拼接在一起。

一定得记得去环啊!!

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null) {
            return null;
        }
        ListNode dummyLeft = new ListNode(0);
        ListNode dummyRight = new ListNode(0);
        ListNode left = dummyLeft, right = dummyRight;
        ListNode node = head;
        while (node != null) {
            if (node.val < x) {
                left.next = node;
                left = left.next;
            } else {
                right.next = node;
                right = right.next;
            }
            node = node.next;
        }
        /////////////
        right.next = null;
        /////////////
        left.next = dummyRight.next;
        return dummyLeft.next;
        
        // if (head == null) {
        //     return null;
        // }
        // ListNode dummy = new ListNode(0);
        // dummy.next = head;
        // ListNode cur = head;
        // while (cur.val != x && cur.next != null) {
        //     cur = cur.next;
        // }
        // if (cur.val != x) {
        //     return head;
        // } 
        // ListNode ln = head;
        
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值