力扣 206. 反转链表

前置

1
2
3
4
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

递归

1
2
3
4
5
6
def reverseList(head):
if not head or not head.next: return head
end = reverseList(head.next)
head.next.next = head
head.next = None
return end

迭代 1

1
2
3
4
5
6
7
8
def reverseList(head):
if not head or not head.next: return head
pre, cur, nex = None, head, head.next
while nex:
cur.next = pre
pre, cur, nex = cur, nex, nex.next
cur.next = pre
return cur

迭代 2

1
2
3
4
5
6
7
8
def reverseList(head):
if not head or not head.next: return head
pre, cur, nex = None, head, head.next
while cur:
cur.next = pre
pre, cur = cur, nex
if nex: nex = nex.next
return pre
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信