反转链表

反转链表_牛客网

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述
输入一个链表,反转链表后,输出新链表的表头。

非递归方法AC代码:

def ReverseList(self, pHead):
    # write code here
    prev = None
    while pHead:
        curr = pHead
        pHead = pHead.next
        curr.next = prev
        prev = curr
    return prev

递归方法:

def ReverseList(self, pHead, prev=None):
    if not pHead:
        return prev
    n = pHead.next
    pHead.next = prev
    return self.ReverseList(n, pHead)

还在思考怎么让递归调用方法中函数只传入一个参数。

全部评论
self.ReverseList(pHead.next),再把最后的head置于反转好的链表后即可,即pHead.next.next=pHead;pHead.next=None;
点赞 回复 分享
发布于 2020-04-13 13:03
请问非递归方法中为什么把pHead=pHead.next 写到curr.next = prev下边就不行了,这是python的什么机制吗,求解释
点赞 回复 分享
发布于 2019-09-24 19:01

相关推荐

评论
8
收藏
分享

创作者周榜

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