# python链表反转(递归)

class ListNode():
def __init__(self,x):
self.val =x
self.next = None

def printNode(head):
curr=head
while curr is not None:
print(curr.val,end=' -> ')
curr=curr.next
print("None")

def reserse(head):
if head is None:
return
temp = head.next
prev = None
curr = head
while curr is not None:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev

def reserseBetween(head, m, n):
def reverse(root, prep, k):
curr = root
prev = None
temp = None
while curr is not None and k>0:
temp = curr.next
curr.next = prev
prev = curr
curr= temp
k -=1
root.next= temp
prep.next= prev
return prev
dummy = ListNode(-1)
dummy.next = head
k = 0
p = dummy
start = None
while p is not None:
if k==m:
start = p
if k==n+1:
reverse(start.next, start, n-m+1)
return dummy.next
k +=1
p=p.next

def n_reverse(head, start_pos, n, repeat=True):
def reverse(root, prep, k):
curr = root
prev = None
temp = None
while curr is not None and k>0:
temp = curr.next
curr.next = prev
prev = curr
curr= temp
k -=1
root.next= temp
prep.next= prev
return root
if start_pos <1:
raise ValueError("Start position should be greater than 0")
dummy = ListNode(-1)
dummy.next = head
k = 0
p = dummy
start = None
while p is not None:
if k == start_pos:
start = p
if k > 1 and k%n==1:
start = reverse(start.next, start, n)
if not repeat:
return dummy.next
k +=1
p=p.next
return dummy.next

def reverse2(head):
if head.next is None : return head#or head.next==None:
result = reverse(head.next)
#printNode(result)
head.next.next = head
head.next = None
return result

n=10
l0=ListNode(0)
for i in range(1,n):
exec(f"l{i}=ListNode({i})")
exec(f"l{i-1}.next=l{i}")

printNode(l0)
printNode(reverse(l0))

10-08                                                                          09-16 4899
07-19 2414
08-20 1918
02-10 54
02-20 123
12-05 17
09-16 49
02-10 101
06-11 1661
04-19 172
07-05 2万+
06-26 5344
12-11 1万+
01-26 6214
04-04 1万+
05-15 6088
07-16 1万+
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客