[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