码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode--Swap Nodes in Pairs

时间:2016-11-26 20:04:07      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:leetcode   方法   pairs   ppa   ext   val   turn   nod   air   

最傻的方法:

    ListNode *swapPairs(ListNode *head) {
        if (head == NULL)
            return NULL;
        ListNode *temp = new ListNode(0);
        ListNode *head_2 = temp;
        while (head != NULL && head->next != NULL) {
            temp = temp->next = new ListNode(head->next->val);
            temp = temp->next = new ListNode(head->val);
            head = head->next->next;
        }
        if (head != NULL)
            temp->next = head;
        return head_2->next;
    }

好一点的方法

    ListNode* swapPairs(ListNode* head) {
        if(!head || !head->next)
            return head;
        ListNode * temp = head->next;
        head->next = swapPairs(temp->next);
        temp->next = head;
        return temp;
    }

 

Leetcode--Swap Nodes in Pairs

标签:leetcode   方法   pairs   ppa   ext   val   turn   nod   air   

原文地址:http://www.cnblogs.com/INnoVationv2/p/6104761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!