题解 | #划分链表#
划分链表
http://www.nowcoder.com/practice/1dc1036be38f45f19000e48abe00b12f
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 用双指针,一个指向开头,一个指向结尾,从开头遍历到结尾,如果当前值比x大,则放到链表尾部,否则继续移动
# @param head ListNode类
# @param x int整型
# @return ListNode类
#
class Solution:
def partition(self , head , x ):
# write code here
if head==None or head.next==None:
return head
new_head=ListNode(0)
new_head.next=head
right=head
n=0
while right.next:
n+=1
right=right.next
print(n)
left=head
pre=new_head
while n>=0:
n-=1
print(left.val,x)
if left.val>=x:
temp=left
left=left.next
pre.next=temp.next
temp.next=None
right.next=temp
right=temp
else:
pre=pre.next
left=left.next
return new_head.next