首页 > 其他 > 详细

LeetCode 24. Swap Nodes in Pairs

时间:2020-02-22 22:09:13      阅读:47      评论:0      收藏:0      [点我收藏+]

题意:交换链表中每两个相邻节点,不能修改节点的val值。

分析:递归。如果以第三个结点为头结点的链表已经两两交换完毕(这一步递归实现---swapPairs(head -> next -> next)),则接下来,只需交换前两个节点,再将第一个节点的next指向“以第三个结点为头结点的链表两两交换后”的链表。

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

  

LeetCode 24. Swap Nodes in Pairs

原文:https://www.cnblogs.com/tyty-Somnuspoppy/p/12347359.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!