①想的比较简单,就是新建n个节点,然后采用头插的方式。然后输出
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
newNode = ListNode()
while head:
temp = ListNode(head.val)
temp.next = newNode.next
newNode.next = temp
head = head.next
return newNode.next
#执行用时:40 ms, 在所有 Python3 提交中击败了49.78%的用户
#内存消耗:16.3 MB, 在所有 Python3 提交中击败了20.10%的用户
②上面的过于繁琐了,而且开辟了额外的空间。所以这里直接对链表进行操作,使用头插法,建立新的链表,使用一个头节点作为标记。
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
preNode = ListNode()
while head:
temp1 = head.next
head.next = preNode.next
preNode.next = head
head = temp1
return preNode.next
#执行用时:28 ms, 在所有 Python3 提交中击败了95.61%的用户
#内存消耗:15.4 MB, 在所有 Python3 提交中击败了96.00%的用户
------看了题解之后:可以有递归的操作,这里和合并链表那个有点像,都是通过递归的方法修改了后面的节点
开始不太懂,后来发现这个res只是一个幌子。。重点是cur,next = pre,这样后面就指向了前面。
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def recur(cur, pre):
if not cur: return pre # 终止条件
res = recur(cur.next, cur) # 递归后继节点
cur.next = pre # 修改节点引用指向
return res # 返回反转链表的头节点
return recur(head, None) # 调用递归并返回