zoukankan      html  css  js  c++  java
  • [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 

  • 相关阅读:
    Licp
    [持续更新]Python 笔记
    求 LCA 的三种方法
    一些题目(4)
    欧几里得算法与扩展欧几里得算法
    最近打的三场比赛的总结
    10day2
    10day1
    chrome谷歌浏览器插件制作简易教程
    nodejs net模块
  • 原文地址:https://www.cnblogs.com/chruny/p/5088629.html
Copyright © 2011-2022 走看看