Leetcode-每日一题【24.两两交换链表中的节点】
发布人:shili8
发布时间:2025-01-01 12:22
阅读次数:0
**两两交换链表中的节点**
**描述:**
给定一个单链表的头部, 交换链表中每两个相邻的节点。
**示例1:**
输入:`1 ->2 ->3 ->4`
输出:`2 ->1 ->4 ->3`
**示例2:**
输入:`7 ->9 ->6 ->5 -> None`
输出:`9 ->7 ->5 ->6 -> None`
**解决方案:**
我们可以使用一个辅助函数来交换链表中的每两个相邻的节点。这个函数会将原来的链表头部作为新的链表头部, 然后交换链表中每两个相邻的节点。
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x self.next = Nonedef swapPairs(head: ListNode) -> ListNode:
# 如果链表为空或只有一个元素, 则不需要交换 if not head or not head.next:
return head # 将原来的链表头部作为新的链表头部 new_head = head.next # 交换链表中每两个相邻的节点 head.next = swapPairs(new_head.next)
new_head.next = head # 返回新的链表头部 return new_head# 测试函数def printList(head: ListNode) -> None:
while head:
print(head.val, end=" ")
head = head.next print()
# 测试用例head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
print("原链表:")
printList(head)
new_head = swapPairs(head)
print("交换后链表:")
printList(new_head)
**输出:**
原链表: 1234交换后链表: 2143
**时间复杂度:** O(n), 其中 n 是链表中的节点数。
**空间复杂度:** O(1), 因为我们只使用了常数大小的额外空间。

