单链表翻转 Python 实现
111 字小于 1 分钟
2024-12-01
循环反转单链表
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
def list_reverse(head):
if head is None or head.next is None:
return head
pre = None
cur = head
h = head
while cur:
h = cur
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return h
递归实现单链表反转
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
def recurse(head,newhead):
if head is None:
return
if head.next is None:
newhead = head
else:
newhead = recurse(head.next,newhead)
head.next.next = head
head.next = None
return newhead