题目链接:206.反转链表
难度:简单
描述:
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
提示:
链表中的结点数是[0, 5000]
。
题解
思路:
没什么好说的。
# 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:
prev = None
cur = head
while cur is not None:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev
# 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
# 找到最后一个有效节点
ret = self.reverseList(head.next)
head.next.next = head
head.next = None
return ret