[LeetCode]题解(python):086-Partition List
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode]题解(python):086-Partition List
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目來源:
https://leetcode.com/problems/partition-list/
?
題意分析:
給定一個(gè)鏈表和一個(gè)target,將比target小的所有節(jié)點(diǎn)放到左邊,大于或者等于的的全部放到右邊。比如1->4->3->2->5->2,如果target為3,那么返回1->2->2->4->3->5。
?
題目思路:
建立兩個(gè)鏈表,遍歷給出的鏈表,如果節(jié)點(diǎn)比target小放到左邊鏈表,否則放到右邊的鏈表。最后將兩個(gè)鏈表連接起來。
?
代碼(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
?
?
轉(zhuǎn)載請注明出處:http://www.cnblogs.com/chruny/p/5088629.html?
轉(zhuǎn)載于:https://www.cnblogs.com/chruny/p/5088629.html
總結(jié)
以上是生活随笔為你收集整理的[LeetCode]题解(python):086-Partition List的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 怎么实现日期转中文
- 下一篇: Python之IPython开发实践