题目 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
解1 迭代
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head || !head->next) return head;
ListNode* pLast = head;
ListNode*pNode = pLast->next;
ListNode* pPre = NULL;
head = pNode;
while(pLast && pNode)
{
pLast->next = pNode->next;
pNode->next = pLast;
if(pPre)
pPre->next = pNode;
pPre = pLast;
pLast = pLast->next;
if(pLast)
pNode = pLast->next;
else
pNode = NULL;
}
return head;
}
};
解2 递归
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
//链表有0个或1个元素,返回
if(!head || !head->next) return head;
//以链表两个元素进行操作,pNode取第二个元素
ListNode* pNode = head->next;
//处理后两个元素,并返回个head->next;
head->next = swapPairs(pNode->next);
pNode->next = head;
//返回pNode
return pNode;
}
};