剑指offer刷题-反转链表

版权声明:虽然本文为博主原创文章,不过随便转载,但必须留下出处。 https://blog.csdn.net/Fighting_Dreamer/article/details/82928703

时间限制:1秒 空间限制:32768K 热度指数:358600
本题知识点: 链表 题目描述 输入一个链表,反转链表后,输出新链表的表头。

问题分析

新建一个节点,不断地将原来的链表的头节点复制到新建的节点前面。

# -*- 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 == None:
            return None
        else:
            newList =  ListNode(pHead.val)
            while pHead.next !=None:
                pHead = pHead.next
                nHead =ListNode(pHead.val)
                nHead.next = newList
                newList = nHead
            return newList

猜你喜欢

转载自blog.csdn.net/Fighting_Dreamer/article/details/82928703
今日推荐