leetcodeday24 –两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

输入:head = [1,2,3,4]
输出:[2,1,4,3]

代码:

# [24] 两两交换链表中的节点
#

# @lc code=start
# 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: ListNode) -> ListNode:
        # head0 = ListNode(0,head)
        if head==None or head.next==None:
            return head
        head0=head
        headr=head.next

        while head0!=None:
            head1=head0
            head2=head0.next
            head3=head2.next
            #print(head3.val)
            head2.next=head1
            if head3==None:    
                head1.next=None
                #print("is 1")
                return headr
            if head3.next==None:
                head1.next=head3
                #print("is 2")

                return headr
            else:
                head1.next=head3.next
                #print(head3.val)
                #print("is 0")

                head0=head3
                #print(head0.val)
        return headr

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注