Python 24 twenty-two switching node in the linked list - Leetcode

Disclaimer: This article is original, All Rights Reserved https://blog.csdn.net/weixin_41864878/article/details/91362046

Given a list pairwise exchange with adjacent nodes, and return the list to the exchange.

You can not just simply change the internal node values, but need to be the actual node exchange.

Example:

Given 1-> 2-> 3-> 4, you should return 2-> 1-> 4-> 3.

The wording of the question about recursion and see who Lively Gangster blog glance, address: http://lylblog.cn/blog/4
I stick to the core of the idea of drawing up
Here Insert Picture Description
this question in fact usually macroscopic considered to head head.next head.next.next three nodes, of course, is to address the first two nodes of exchange, for the third node my understanding is that the use of recursion when it is a recursive function returns Therefore head.next after exchange = function (head.next.next)

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next: return head
        node = head.next
        head.next = self.swapPairs(node.next)
        node.next = head
        return node

Guess you like

Origin blog.csdn.net/weixin_41864878/article/details/91362046