题目:
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;
}
};