# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
p=ListNode(0) #0(头结点)->1(交换对前)->2(交换对后)->3(后结点)
#交换一对后为0->2->1->3
p.next=head
h1=p #操作对象为头结点+1对链表(后移后头结点为要交换的链表对之前那个)
while h1.next and h1.next.next:
h2=h1.next
h1.next=h2.next
h2.next=h2.next.next #h1.next.next #先交换 1.头 ->交换对后,2.交换对前->后结点,3交换对后->交换对前,4头结 点往后俩个
h1.next.next=h2
h1=h1.next.next
return p.next
"""
:type head: ListNode
:rtype: ListNode
"""
本文介绍了一种在单链表中成对交换节点的算法实现。通过定义链表节点类ListNode,使用辅助节点简化了交换过程,确保了链表的正确性和完整性。算法在保证O(n)时间复杂度的同时,提供了清晰的代码示例。
8628

被折叠的 条评论
为什么被折叠?



