LeetCode—24. Swap Nodes in Pairs

Type:medium

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.


Example:

Given1->2->3->4, you should return the list as2->1->4->3.


给定一个链表,两个两个一组,交换数值。

利用递归法,其本质是回溯法。先对最后的一组数据进行交换(最后一组只有1个或0个有效数值),返回这个head,即是给上一组的第一个数值的next地址,再将temp(第二个数)的next赋为head,最后上一组的处理返回temp的地址。


/**

* 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 || !head->next) return head;

        ListNode* temp = head->next;

        head->next = swapPairs(head->next->next);

        temp->next = head;

        return temp;

    }

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容