题目来源
https://leetcode.com/problems/partition-list/
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
题意分析
Input:
:type head: ListNode
:type x: int
Output:
:rtype: ListNode
Conditions:将一个list分成两个list,其中一个list的所有元素都小于x,另外一个list的所有元素都大于或等于x,注意要保持稳定性(即相等的元素,原来什么顺序就是什么顺序)
题目思路
设两个头节点,之后扩展这两个list就好,head1 list的所有元素都小于x,head2 list的所有元素都大于或等于x,然后将head2 list加到head1 list后面,然后返回需要的list 起点。
AC代码(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 head1 = ListNode(0) 15 head2 = ListNode(0) 16 17 p1 = head1 18 p2 = head2 19 20 tmp = head 21 22 while tmp: 23 if tmp.val < x: 24 p1.next = tmp 25 tmp = tmp.next 26 p1 = p1.next 27 p1.next = None 28 else: 29 p2.next = tmp 30 tmp = tmp.next 31 p2 = p2.next 32 p2.next = None 33 p1.next = head2.next 34 return head1.next 35