题解 | #重排链表#

重排链表

http://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
# 
# @param head ListNode类 
# @return void
#
class Solution:
    def reorderList(self , head ):
        # write code here
        
        if not head or not head.next or not head.next.next: 
            return head
            
        #快慢指针找中间位置
        
        slowptr = head
        fastptr = head
        while fastptr.next and fastptr.next.next:
            slowptr = slowptr.next
            fastptr = fastptr.next.next
        head1 = head
        head2 = slowptr.next
        temp1 = None
        
        #反转后半段链表
        
        while head2:
            temp2 = head2.next
            head2.next = temp1
            temp1 = head2
            head2 = temp2
            
        #顺序合并
        
        head2 = temp1
        while head2:
            temp1 = head1.next
            temp2 = head2.next
            head1.next = head2
            head2.next = temp1
            head1 = temp1
            head2 = temp2
            if head2 == None:
                head1.next = None
        return head
        
        
        
        
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 18:02
好不容易拿到了字节Offer,鼠鼠做后端的,但家里人觉得可能被裁员不稳定,让鼠鼠去投国企,现在好纠结到底该咋选
文档传偷助手:该投就投吧,不过建议别放弃offer 拿到手里的才是最好的
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
05-13 02:01
已编辑
惠州学院 前端工程师
安静的少年在求佛:建议把公司名字写到标题。以后有人想搜就能直接搜到
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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