目录
1 题目
2 题解
3 Python
1 题目
2 题解
正常通过遍历的方法是设置指针顺次遍历,然后将指针改变方向就可以。
递归的方式可以先将链表除第一个节点以外的链表反转,然后将第一个节点连接在反转之后的链表上,再将其指针置空。
3 Python
遍历的写法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
#如果链表为空,或者只有一个节点
if head is None or head.next is None:
#直接返回就可以
return head
#指向前一个节点的指针
pre=None
#当前节点指针
now=head
while now is not None:
#记录下一个要移动到的节点
last=now.next
#反转
now.next=pre
#移动到下一个节点
pre=now
now=last
return pre
递归写法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
#如果链表为空,或者只有一个节点
if head is None or head.next is None:
#直接返回就可以
return head
#反转除第一个节点外的后续链表
newhead=self.reverseList(head.next)
#处理第一个节点
head.next.next=head
head.next=None
return newhead



