题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def ReverseList(self , head: ListNode) -> ListNode:
# write code here
if head is None:
return head
a = []
while head != None:
a.append(head.val)
head = head.next
a = a[::-1]
newL = ListNode(a[0])
res = newL
for j in range(1, len(a)):
newL.next = ListNode(a[j])
newL = newL.next
newL.next = None
return res
主要思路
- 先判断链表为空的情况;
- 再遍历链表,获得链表的值;
- 然后利用Python的切片性质,直接进行反转(或直接从后往前遍历);
- 之后创建新的链表。
需要注意的是:创建新的链表节点的时候是newL.next = ListNode(a[j]),不是newL.next = a[j],更不是newL.val = a[j]。同时需要注意,链表最后要指向None。

