题解 | #反转链表#

反转链表

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
        if not pHead or not pHead.next: #input:{} or {1}
            return pHead
        else:
            current=ListNode(None) #记录目前已生成的反转链表
            while pHead.next!=None:
                pre=ListNode(None) #记录下一个表头
                current.val=pHead.val #好像不写这行也行?
                pre.val=pHead.next.val #set up下一个表头的val
                pre.next=current#表头和现有的反转链表连接
                pHead=pHead.next#pHead 往后移动一步,直到最后一个数
                current=pre#更新当前反转链表
            return pre
全部评论

相关推荐

xxxxOxo:该催就催,想要你的不会因为催就挂,催了就挂的是因为本来就要挂你
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务