# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defreverseList(self, head: Optional[ListNode])-> Optional[ListNode]:ifnot head ornot head.next:return head
pre, cur =None, head
while cur:
nxt = cur.next
cur.next= pre
pre = cur
cur = nxt
return pre
递归
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defreverseList(self, head: Optional[ListNode])-> Optional[ListNode]:ifnot head ornot head.next:return head
last = self.reverseList(head.next)
head.next.next= head
head.next=Nonereturn last
classSolution{publicListNodereverseList(ListNode head){if(head ==null|| head.next ==null){return head;}ListNode pre =null, cur = head;while(cur !=null){ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;}return pre;}}