24 两两交换链表中的节点

class ListNode:    def __init__(self, x):        self.val = x        self.next = Noneclass Solution:    def swapPairs(self, head: ListNode) -> ListNode:        # 定义一个节点,并将它指向头结点        node = ListNode(0)        cur = node        cur.next = head        # 这样写是由于奇数节点最后一个节点不用反转        while cur.next and cur.next.next:            # 定义节点表明须要反转的节点。            node1,node2 = cur.next,cur.next.next            # 进行反转            cur.next,node2.next,node1.next = node2,node1,node2.next            # 更新当前节点到下两个须要反转的节点前。            cur = node1        return node.next
相关文章
相关标签/搜索