开始之前先给自己打个鸡血吧:
A journey of a thousand miles begins with a single step. 千里之行始于足下。
题源:https://leetcode.cn/problems/UHnkqh/
题目详情:
给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。
思路
递归实现。第一次写的时候根本没搞懂递归原理·······第二段代码贴出正确的递归方法。具体如下:
代码
python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return
if head.next==None:
return head
l=head
while l.next.next:
l=l.next
p=l.next
p.next=l
l.next=None
self.reverseList(head)
return p
可怜的执行效率····························································
正确实现: