链表成对调换

把1-->2-->3-->4变成2-->1-->4-->3

我主要写了2个方法:

方法一:用递归调用

方法二:直接调换

注意:返回的是调换后的链表头结点


class Solution(object):
    def swapPairs(self,head):
        #使用递归调用
        if not head or not head.next:
            return head
        tmp=head.next
        head.next=self.swapPairs(tmp.next)
        tmp.next=head
        return tmp
    def swapPairs2(self,head):
        pre=dummy=Node(0)
        pre.next=head
        while pre.next and pre.next.next:
            a=pre.next
            b=pre.next.next
            pre.next,a.next,b.next=b,b.next,a
            pre=a
        return dummy.next

猜你喜欢

转载自blog.csdn.net/xiaolangmin/article/details/89885717