问题描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
双指针方法
- 比如一个链表的第一个结点值为1,第二个为2,…,最后一个为5,如上图
- 定义两个指针 cur 和 pre ,和一个临时指针 temp ,让 cur 指向 head (第一个结点1),pre 指向空 (NULL)
- 只要 cur 一直存在,则进入 while 循环
- 令 temp 指针指向 cur 的下一个结点(即2),cur 的下一个指针指向 pre (目前为空)
- 然后将 cur 和 pre 都往后移一个结点。要注意先移动 pre
- 依次循环
- 最后返回 pre
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = None
while cur :
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
递归方法
- 判断 head 或 head.next 是否为空,若为空,则返回 head
- 定义一个 n_head 以 head.next 为参数递归执行该函数,递归结束后,此时 head 为4,head.next 为5
- 令 head.next.next=head,即令 5 的下一个指针指向 4,从而实现反转,依次递归。。。
- 最后返回 n_head
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
n_head=self.reverseList(head.next)
head.next.next=head
head.next=None
return n_head