成对交换结点(swap-nodes-in-pairs)

  • 问题描述
    Given a linked list, swap every two adjacent nodes and return its head.
    For example,
    Given1->2->3->4, you should return the list as2->1->4->3.
    Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
    交换相邻的两个节点,并返回头结点。
    要求不能改变节点的值,而是改变节点本身,且只能使用常量的空间。

  • 问题分析
    采用递归实现。
    若头结点head为空或head->next为空,那么返回head;
    否则改变结点指向,先令head->next指向pNext->next,再令pNext->next指向head,如下图所示:

  • 代码实现

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if(head==NULL || head->next==NULL) return head;
        else{
            ListNode *pNext=head->next;
            head->next=swapPairs(pNext->next);
            pNext->next=head;
            return pNext;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/ananbei/article/details/81121589