[LeetCode]题解(python):086-Partition List

题目来源:

  https://leetcode.com/problems/partition-list/


 

题意分析:

  给定一个链表和一个target,将比target小的所有节点放到左边,大于或者等于的的全部放到右边。比如1->4->3->2->5->2,如果target为3,那么返回1->2->2->4->3->5。


 

题目思路:

  建立两个链表,遍历给出的链表,如果节点比target小放到左边链表,否则放到右边的链表。最后将两个链表连接起来。


 

代码(Python):

  

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def partition(self, head, x):
 9         """
10         :type head: ListNode
11         :type x: int
12         :rtype: ListNode
13         """
14         ans = ListNode(0)
15         left,right = ListNode(0),ListNode(0)
16         p1,p2 = left,right
17         while head:
18             tmp = ListNode(head.val)
19             if head.val < x:
20                 left.next = tmp;left = left.next
21             else:
22                 right.next = tmp;right = right.next
23             head = head.next
24         left.next = p2.next
25         return p1.next
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/5088629.html 

转载于:https://www.cnblogs.com/chruny/p/5088629.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值