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 

  • 相关阅读:
    快速排序
    冒泡排序算法
    设计模式之工厂方法模式
    调用存储过程修改
    取出字符串中的回车空格
    调用存储过程实例
    C++左值
    cocos2d-x 不规则形状按钮的点击判定
    C/C++
    字符函数库 cctype
  • 原文地址:https://www.cnblogs.com/chruny/p/5088629.html
Copyright © 2011-2022 走看看