怎么说,,,迭代的时候一定要注意首和尾。不然就会无限循环
1、迭代
class ListNode:
def __init__(self, x=None, next=None):
self.val = x
self.next = None
l1 = ListNode(1)
head = l1
for i in range(2, 9):
head.next = ListNode(i)
head = head.next
head = l1
# 迭代
dunmmy = ListNode(0)
dunmmy.next = head
pre = head
cur = head
a = dunmmy
while cur and cur.next:
cur = cur.next
a.next = cur
t = cur.next
cur.next = pre
a = pre
pre = t
cur = pre
a.next = cur # 防止无限循环
head = dunmmy.next
while head != None:
print(head.val)
head = head.next
2、递归,要注意当两个参数出界时,可以换成一个参数啊,就不用这么多限制了
class ListNode:
def __init__(self, x=None, next=None):
self.val = x
self.next = None
l1 = ListNode(1)
head = l1
for i in range(2, 9):
head.next = ListNode(i)
head = head.next
head = l1
#递归
def chang2(pre, cur):
if pre == None or cur == None:
return pre
t = cur.next
cur.next = pre
if t == None:
return None
pre.next = chang2(t, t.next)
return cur
head = chang2(head, head.next)
while head != None:
print(head.val)
head = head.next
还是应该多看看参考答案,找找差距,,



