# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 方法1:迭代
# 如果list为空则直接返回head
# 如果list只有一个值,也直接返回head
# 搞一个dummy
# if head == None:
# return head
# elif head.next == None:
# return head
# p1 = head
# p2 = head.next
# dummy = ListNode()
# dummy.next = head
# p1_post = dummy
# while p1 and p2:
# 交换p1, p2
# p2_pre = p2.next
# p1.next = p2.next
# p2.next = p1
# p1_post.next = p2
# p1_post = p1
# # p1, p2挪位为下面两个要swap的
# p1 = p2_pre
# if p1:
# p2 = p1.next
# return dummy.next
# 方法2:递归 我觉得这题可以用递归唉
if head == None:
return head
elif head.next == None:
return head
else:
p1 = head
p2 = head.next
# 交换p1, p2
# p2_pre = p2.next
# p1.next = p2.next
# p2.next = p1
# p1_post.next = p2
p2_pre = self.swapPairs(p2.next)
p1.next = p2_pre
p2.next = p1
return p2
24.两两交换链表中的节点
最新推荐文章于 2024-11-05 15:32:33 发布