[leetcode]Swap Nodes in Pairs

有意思。此题最简单的解法是递归,在纸上画一下就看出来了。

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		if (!head || !head->next) return head;

		ListNode* n1 = head;
		ListNode* n2 = n1->next;

		ListNode* n3 = n2->next;
		n2->next = n1;
		n1->next = swapPairs(n3);

		return n2;
    }
};

python3 非递归

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head
        tmp = dummy
        while tmp and tmp.next and tmp.next.next:
            a = tmp.next
            b = tmp.next.next
            # tmp -> a -> b
            c = b.next
            tmp.next = b
            b.next = a
            a.next = c
            tmp = a
        return dummy.next

  

原文地址:https://www.cnblogs.com/lautsie/p/3226632.html