Leetcode 24. Swap Nodes in Pairs

文章作者:Tyan
博客:noahsnail.com  |  ****  |  简书

1. Description

Leetcode 24. Swap Nodes in Pairs

2. Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head || !head->next) {
            return head;
        }
        ListNode* latter = head->next;
        head->next = swapPairs(latter->next);
        latter->next = head;
        return latter;
    }
};

Reference

  1. https://leetcode.com/problems/swap-nodes-in-pairs/description/