1. 题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
2. 方法一迭代法
2.1. 代码
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode* Temp=head->next;
head->next=swapPairs(head->next->next);
Temp->next=head;
return Temp;
}
2.2. 结果
3. 方法二
3.1. 代码
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode Node(-1);
Node.next=head;
ListNode* Pre=&Node;
while(Pre->next!=NULL&&Pre->next->next!=NULL)
{
ListNode *L1=Pre->next, *L2=L1->next,*Next=L2->next;
Pre->next=L2;
L2->next=L1;
L1->next=Next;
Pre=L1;
}
return Node.next;
}
};