题解 | #反转链表#

反转链表

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

对 pHead的理解

我在最开始的回答中把pHead也当作要使用ListNode数据结构来表示。但是这个想法是错误的,
图片说明
但是,在代码片段中,默认pHead只是一个指针。如下图所示:
图片说明

双指针思路的代码

# -*- 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 pHead is None: return
        curN = pHead
        pHead = curN.next
        curN.next = None
        while pHead:
            nextN = pHead
            pHead = nextN.next
            nextN.next = curN
            curN = nextN
        pHead = curN
        return pHead

以上的代码由于26%的程序。还不算高,我参考下别人的代码。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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