题解 | #重排链表#

重排链表

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

用列表存储每个节点,依次弹出首位、末位的节点,组成新链表即可。 没有新建链表,空间复杂度O(n),时间复杂度O(2n)=O(n)

# 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 head is None:
            return None
        link=[]
        while head!=None:
            tmp=head
            head=head.next
            tmp.next=None
            link.append(tmp)
            
        newhead=link.pop(0)
        tmp=newhead
        front=False
        while len(link)>0:
            if front:
                tmp.next=link.pop(0)
                front=False
            else:
                tmp.next=link.pop()
                front=True
            tmp=tmp.next
        return newhead

全部评论
厉害了,那么多代码就看懂这一个
点赞
送花
回复
分享
发布于 2022-09-14 17:32 陕西

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务