题解 | #反转链表#

反转链表

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

# 一般思路
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        pre = None
        cur = pHead
        nex = None
        
        while cur:
            # nex为当前节点的下一个节点
            nex = cur.next
            # 当前节点的下一个节点为目前的前一个节点
            cur.next = pre
            
            #===为下次循环做准备
            # 前节点更新(当前节点)
            # 往下进行
            # 最后一次:pre为最后一个节点,cur为空,跳出while循环
            pre = cur
            cur = nex 
        return pre;
# 递归
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead: return None
        if not pHead.next: return pHead
        headNode = self.ReverseList(pHead.next)
        pHead.next.next = pHead
        pHead.next = None
        return headNode


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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