题解 | #划分链表#

划分链表

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
全部评论

相关推荐

牛客837006795号:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务