前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >打卡群刷题总结0729——分隔链表

打卡群刷题总结0729——分隔链表

作者头像
木又AI帮
发布2020-08-04 17:49:58
2350
发布2020-08-04 17:49:58
举报
文章被收录于专栏:木又AI帮木又AI帮

题目:86. 分隔链表

链接:https://leetcode-cn.com/problems/partition-list

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 你应当保留两个分区中每个节点的初始相对位置。 示例: 输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5

解题:

1、使用两个链表分别存储<x的数和>=x的数,最后将两个链表进行拼接。

代码:

代码语言:javascript
复制
# 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
        """
        head1 = ListNode(0)
        head2 = ListNode(0)
        p = head1
        q = head2
        
        cur = head
        while cur:
            if cur.val < x:
                p.next = cur
                p = p.next
            else:
                q.next = cur
                q = q.next
            cur = cur.next
        p.next = head2.next
        q.next = None
        return head1.next
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 链接:https://leetcode-cn.com/problems/partition-list
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档