leetcode-24-swap nodes in pairs

Problem Description:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题目大意:

交换每一对链表的顺序。

Solutions:

用一个递归的办法可以简单的完成这个问题,注意边界。 当然用非递归的办法也可以,不过写法并不够简洁,本文仅提供递归的解法。

Code in C++:

/**
 * 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 * nextp = head->next->next;
        ListNode * tem = head->next;
        head->next = swapPairs(nextp);
        tem->next = head;
        return tem;
    }
};