# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
#若不存在节点或只存在一个节点
if not head or not head.next:
return head
Head = ListNode(0) #辅助头结点
Head.next = head
p = head.next #从第1个节点开始
head.next = None #第0个节点封尾,避免环链
while p:
tmp = p
p = p.next
tmp.next = Head.next #头插法
Head.next = tmp
return Head.next
initial:
1 -> 2 -> 3 -> 4 -> 5
after reverseList(2):
1 -> 2 <- 3 <- 4 <- 5
|
null
after operate on 1:
null <- 1 <- 2 <- 3 <- 4 <- 5
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next: #边界
return head
newHead = self.reverseList(head.next)
head.next.next = head #反转链
head.next = None #原链置空,防止环链
return newHead