24. Swap Nodes in Pairs

题目:

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 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

 

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

 

 

思路1:

第一反应这应该是递归问题,我写的方法是用栈模拟,可能相对较长一些。首先全部压入栈,然后如果数量是奇数,则先把栈顶那个拿出来,当作最尾;如果为偶数,直接把尾设成空。然后这时栈内元素就是偶数个了,每次拿两个,然后交换即可。这里记得如果之前的尾其实就是我们要反悔的root,如果是空我们就把当前的root赋值给尾,否则就直接把当前的尾连接到之前的尾上即可。

 

 

代码1:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head)
            return head;
        stack<ListNode*> s;
        while(head)
        {
            s.push(head);
            head=head->next;
        }
        ListNode* ans=NULL;
        if(s.size()%2!=0)
        {
            ans=s.top();
            s.pop();
        }
        while(s.size())
        {
            ListNode* q=s.top();
            s.pop();
            ListNode* p=s.top();
            s.pop();
            q->next=p;
            if(!ans)
            {
                ans=q;
                p->next=NULL;
            }
            else
            {
                p->next=ans;
                ans=q;
            }
        }
        return ans;  
    }
};

 

 

思路2:

用递归做即可。

 

 

代码2:

class Solution {
public:
    //invert the first 2 and then recurse for the rest
    ListNode* swapPairs(ListNode* head) {
        //base case here
        if(!head || !head->next) return head;
        //Swapping part happens here, please draw to visualize
        ListNode *temp = head->next;
        head->next = swapPairs(temp->next); 
        temp->next = head;

        return temp;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值