86. Partition List

题目要求:

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Examples:

Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

解题思路:
  • 使用两个链表: < target :插入到less_head链表里;> target :插入到more_head链表里,最后将两个链表相连接。
  • 示意图
代码:
class ListNode():
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, repr(self.next))


class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        less_head = ListNode(0)
        more_head = ListNode(0)
        less_ptr = less_head
        more_ptr = more_head

        while head:
            if head.val < x:
                less_ptr.next = head
                less_ptr = head
                head = head.next
                less_ptr.next = None

            else:
                more_ptr.next = head
                more_ptr = head
                head = head.next
                more_ptr.next = None

        less_ptr.next = more_head.next

        return less_head.next


if __name__ == "__main__":
    head, head.next, head.next.next = ListNode(1), ListNode(5), ListNode(3)
    head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4)
    head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5)

    print(Solution().partition(head, 4))
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,854评论 0 10
  • 老公,我好想你,舍不得放下电话,想多听听你的声音,想黏着你。如果没有你,我就是一个空心的人,我的心就是你。你要是要...
    涛之源阅读 2,152评论 0 0
  • 估计很多人都和我一样,很久没有在电视机前揪着一颗心完完整整的看完一场比赛了。今天,中国女排决赛在首局失利的情况下气...
    天竹萧萧阅读 1,084评论 0 8
  • 《爱的五种语言》 P66-67 精心的会话 请写出你的: 【I】 是什么? 我们都善于思考,善于解决问题,同时哪怕...
    当梦醒来以后阅读 365评论 1 0
  • 凌波添绿,见燕穿柳雨,年年春色。 鹭立沙汀鱼跃水,山远斜江天阔。 飞絮吹烟,琉璃鸭戏,数峰平渔火。 清歌浊酒,洞箫...
    眉间飞雪阅读 558评论 19 21

友情链接更多精彩内容