您的位置:首页 > Web前端 > Node.js

leetcode之Swap Nodes in Pairs

2016-04-05 12:08 501 查看
看到这道题目竟然也可以使用递归,我的第一反应是很惊奇,此前都是用到了好几个指针,相互指来指去,稍不留意就会出错,很是麻烦。用到了递归之后就会变得很容易。这里

给出递归的代码,代码量也一下子少了不少,当然牺牲了时间复杂度

(1)C语言实现

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     struct ListNode *next;

 * };

 */

struct ListNode* swapPairs(struct ListNode* head) {

    if(head == NULL || head->next == NULL)

        return head;

    struct ListNode* n = head->next;

    head->next = swapPairs(head->next->next);

    n->next = head;

    return n;

}

(2)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 == NULL || head->next == NULL)

            return head;

        ListNode* p = head->next;

        head->next = swapPairs(head->next->next);

        p->next = head;

        return p;

    }

};

(3)java实现

/**

 * Definition for singly-linked list.

 * public class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) { val = x; }

 * }

 */

public class Solution {

    public ListNode swapPairs(ListNode head) {

        if(head == null || head.next == null)

            return head;

        ListNode n = head.next;

        head.next = swapPairs(head.next.next);

        n.next = head;

        return n;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: