leetcode_86_分隔链表

分隔链表

描述

中等

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例

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

解题

另外定义两个链表,一条放小于x的,一条放大于等于x的

最后两条接起来

# python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        head_big = ListNode(-1)
        head_small = ListNode(-1)

        p_big = head_big
        p_small = head_small

        while head:
            if head.val >= x:
                p_big.next = head
                p_big = p_big.next
            else:
                p_small.next = head
                p_small = p_small.next
            head = head.next
        
        p_small.next = head_big.next
        p_big.next = None

        return head_small.next

// java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode head_big = new ListNode();
        ListNode head_small = new ListNode();

        ListNode p_big = head_big;
        ListNode p_small = head_small;

        while (head != null) {
            if (head.val >= x) {
                p_big.next = head;
                p_big = p_big.next;
            } else {
                p_small.next = head;
                p_small = p_small.next;
            }
            head = head.next;
        }

        p_small.next = head_big.next;
        p_big.next = null;

        return head_small.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值