题解 | #重排链表#

重排链表

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

相关推荐

10-28 11:04
已编辑
美团_后端实习生(实习员工)
一个2人:我说几个点吧,你的实习经历写的让人觉得毫无含金量,你没有挖掘你需求里的 亮点, 让人觉得你不仅打杂还摆烂。然后你的简历太长了🤣你这个实习经历看完,估计没几个人愿意接着看下去, sdk, 索引这种东西单拎出来说太顶真了兄弟,好好优化下简历吧
点赞 评论 收藏
分享
像好涩一样好学:这公司我也拿过 基本明确周六加班 工资还凑活 另外下次镜头往上点儿
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务