题解 | #重排链表#

重排链表

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
        # --------------------#
        # 首先判断head是否为空
        # --------------------#
        if head is None:
            return
        # -------------------------------------#
        # 建立前向和后向数组,并获取head的长度
        # -------------------------------------#
        front = []
        back = []
        count = self.count_num(head)
        # -------------------------------------------#
        # 将题目要求的奇数个存入front,偶数个存入back
        # -------------------------------------------#
        for i in range(count):
            mum = head
            head = head.next
            mum.next = None
            if i < int(count/2)+1:
                front.append(mum)
            else:
                back.append(mum)
        # --------------------#
        # 开始建立新的链表
        # --------------------#
        newhead = front[0]
        temp = newhead
        if count%2 == 1 or count == 2:
            for i in range(len(front)-1):
                if len(back) > 0:
                    temp.next = back[len(back) - i - 1]
                    temp = temp.next
                    temp.next = front[i+1]
                    temp = temp.next
                else:
                    temp.next = front[i+1]
                    temp = temp.next
        else:
            for i in range(len(front)-2):
                temp.next = back[len(back) - i - 1]
                temp = temp.next
                temp.next = front[i+1]
                temp = temp.next
                if i == len(front)-3:
                    temp.next = front[i+2]
                    temp = temp.next
        return newhead
    
    # --------------------#
    # 计算head的长度的函数
    # --------------------#
    def count_num(self, head):
        count = 0
        while head != None:
            count += 1
            head = head.next
        return count
        
全部评论

相关推荐

安静的垂耳兔在泡澡:ks已经第八次投递了,它起码挂了还让你再投,不错了
点赞 评论 收藏
分享
11-09 11:01
济南大学 Java
Java抽象带篮子:外卖项目真得美化一下,可以看看我的详细的外卖话术帖子
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务