题解 | #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

1. 递归

import sys
sys.setrecursionlimit(10000)  
# 经测试python3解释器默认递归最大深度为3000,所以当链表长度大于3000的时候,会引发RecursionError异常
class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        if head is None or head.next is None:
            return head
        next_ = head.next
        reverse = self.ReverseList(next_)
        next_.next = head
        head.next = None
        return reverse

2.遍历翻转

class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        new_head = None
        while head:
            tmp = head.next
            head.next = new_head
            new_head = head
            head = tmp
        return new_head
全部评论

相关推荐

星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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