LeetCode-24 Swap Nodes in Pairs

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30986521/article/details/80936600

题目链接

不能直接修改Node里面val的值,但是可以修改Node本身,即通过指针交换Node

/**
 * 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) return head;   //空链表
        if (head->next == NULL) return head;   //只有一个节点
        
        ListNode *p = head, *q = head->next;
        
        p->next = q->next;            //交换前两个
        q->next = p;
        
        p->next = swapPairs(p->next);   //后面的递归处理
        
        return q;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_30986521/article/details/80936600