题目大意:给出一个链表,成对的交换相邻两个元素的节点,要求不能够修改每个节点的值。
算法思想:
1.对于给出的链表判断其节点个数,如果小于2则直接返回链表。
2.设置4个节点指针,分别指向前驱节点,当前节点,后继节点,缓存节点指针。
3.由于没有表头节点,则对于头两个节点单独进行交换。
4.遍历链表,根据先继承后修改的原则,交换相邻的两个节点。移动后继节点时要注意,如果当前节点为空,则后继节点设置为空,否则会报错。
5.返回修改后的链表。
代码如下:
/**
* 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==NULL||head->next==NULL) return head;
ListNode *cp=head,*post=head->next,*pre,*temp;
temp=post->next;
post->next=cp;
cp->next=temp;
head=post;
pre=cp;
cp=cp->next;
if(cp==NULL)
post=NULL;
else
post=cp->next;
while(cp!=NULL&&post!=NULL){
temp=post->next;
post->next=cp;
pre->next=post;
cp->next=temp;
pre=cp;
cp=cp->next;
if(cp==NULL)
post=NULL;
else
post=cp->next;
}
return head;
}
};