Python 链表反转 1、常规 2、递归

反转链表

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

# 解法一:常规修改指针
class Solution:
    def ReverseList(self, pHead):
        # write code here
        if not pHead:
            return None
        pre=None
        while pHead:
            tmp=pHead.next
            pHead.next=pre
            pre=pHead
            pHead=tmp
        return pre    

解法二:递归形式
class Solution:
    def ReverseList(self,pHead):  # pHead=1->2->3->4
        # 定义终止条件:         空值或者只有一个节点的时候,直接返回pHead
        if not pHead or not pHead.next:
            return pHead
        # 递归条件:
        newlist=self.ReverseList(pHead.next)   # pHead.next=2->3->4
        # 第一步,就定义了reverseList函数的功能可以把一个单链表反转
        # 对2->3->4反转之后的结果应该是这样:4->3->2 ,1->2 这是得到newlist
        # 最后修改一下1的指向就可以了,让2->1
        p2=pHead.next # 2
        p2.next=pHead # 2->1
        pHead.next=None  # 1->None
        return newlist
全部评论

相关推荐

机械打工仔:有说的你怀疑一下就行了,直接问也太实诚了
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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