欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swap Nodes in Pairs

程序员文章站 2022-03-05 08:16:53
...

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:

Given 1->2->3->4, you should return the list as 2->1->4->3'

递归法:

/**
 * 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* p1=head,*p2=p1->next;
        ListNode* tmp1=p1->next->next;
        head=p2;
        p2->next=p1;
        p1->next=swapPairs(tmp1);
        return head;
    }
};

 

相关标签: leetcode