题目
思路
用两个指针,记录下来nmax和pre_nmax结点,之后不断插入即可。
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The first node of linked list
@param: x: An integer
@return: A ListNode
"""
def partition(self, head, x):
# write your code here
dummy = ListNode(0)
dummy.next = head
node = head
pre = dummy
nx = None
nmax = None
nmax_pre = dummy
while node:
if not nx and node.val == x:
nx = node
if not nmax:
nmax = node
nmax_pre = pre
node = node.next
pre = pre.next
elif not nmax and node.val > x:
nmax = node
nmax_pre = pre
node = node.next
pre = pre.next
elif node.val < x and nmax:
tmp = node.next
node.next = nmax
nmax_pre.next = node
nmax_pre = node
pre.next = tmp
node = tmp
else:
node = node.next
pre = pre.next
return dummy.next