【LintCode 简单】96. 链表划分

本文介绍了一种链表处理算法,该算法能够将一个给定的单链表中所有节点按给定数值x进行划分,使得所有小于x的节点排在大于等于x的节点前面,同时保持各部分内部节点原有顺序不变。

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

1.问题描述:

给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。

你应该保留两部分内链表节点原有的相对顺序。


2.样例:

给定链表 1->4->3->2->5->2->null,并且 x=3

返回 1->2->2->4->3->5->null


3.代码:

第一种方法:

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: head: The first node of linked list
    @param: x: An integer
    @return: A ListNode
    """
    def partition(self, head, x):
        # write your code here
        if head is None:  
            return head  
        # 新建两个节点  
        first = ListNode(-1)  
        second = ListNode(-1)  
        cur1, cur2 = first, second  
        # 遍历原始链表  
        while head:  
            if head.val < x:  
                cur1.next = head  
                head = head.next  
                cur1 = cur1.next  
            else:  
                cur2.next = head  
                head = head.next  
                cur2 = cur2.next  
        # 合并  
        cur1.next = second.next  
        cur2.next = None  
        return first.next  

第二种方法:

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: head: The first node of linked list
    @param: x: An integer
    @return: A ListNode
    """
    def partition(self, head, x):
        # write your code here
        if head is None:
            return None
        elif head.next is None:
            return head
        else:
            tail=head
            count=1
            while tail.next:
                tail=tail.next
                count+=1
            pre=ListNode(0)
            cur=head
            pre.next=cur
            i=0
            fg=True
            while i<count:
                if cur.val>=x:
                    tail.next=cur
                    pre.next=cur.next
                    tail=cur
                    if fg:
                        head=head.next
                    tail.next=None
                    cur=pre.next
                else:
                    fg=False
                    pre=pre.next
                    cur=cur.next
                i+=1
            return head



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值