86. 分隔链表--PYTHON

在这里插入图片描述

自己1:采用暴力破解法,遍历整个链表序列,将所有小于x的值和大于等于x的值分别存储在两个列表中,并建立两个新链表,并对链表进行拼接。:

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

class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """

        if not head:
            return None

        res = ListNode(-1)
        s_list = list()
        b_list = list()
        res_list = list()
        res_node = ListNode(-1)


        p = head
        while p:
            if int(p.val) < x:
                s_list.append(int(p.val))
            else:
                b_list.append(int(p.val))
            p = p.next
        s_list = s_list[::-1]
        b_list = b_list[::-1]
        res_list = b_list + s_list

        for i in res_list:
            tmp = ListNode(int(i))
            tmp.next = res_node.next
            res_node.next = tmp

        res.next = res_node.next
        return res.next

大佬1:跟自己的思路差不多,大佬用了双指针,没有建立我用的链表,大佬直接建立了两个空的链表,最后将链表连接起来就行了。

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

class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """

        before = before_head = ListNode(0)   #建立两个链表和指向插入位置的指针
        after = after_head = ListNode(0)

        while head:    #遍历整个序列
            if head.val < x:
                before.next = head
                before = before.next
            else:
                after.next = head
                after = after.next

            head = head.next

        after.next = None        #将两个链表进行连接
        before.next = after_head.next

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值