zoukankan      html  css  js  c++  java
  • LeetCode 24. Swap Nodes in Pairs(交换链表中每两个相邻节点)

    题意:交换链表中每两个相邻节点,不能修改节点的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 *second = head -> next;
            ListNode *third = head -> next -> next;
            second -> next = head;
            head -> next = swapPairs(third);
            return second;
        }
    };
    
  • 相关阅读:
    poj 1286
    poj 1815
    poj 3368
    十个利用矩阵乘法解决的经典题目
    poj 1026
    hdu 1394
    poj 3270
    poj 2154
    《重构 改善既有代码的设计》读书笔记2
    Android OpenGL ES: 渐变颜色的三角形
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12347359.html
Copyright © 2011-2022 走看看