Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
思路:
1.空头节点的使用
2.用三个指针,p记录当前的答案链表的尾部,a记录接下来要换的第一个,b记录要换的第二个
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy(-1);//头节点
ListNode *p=&dummy,*a,*b;
p->next=head;
while((a=p->next) && (b=a->next)){//要学会这种在while循环里赋值的方法,可以直接跳出循环
a->next=b->next;
b->next=a;
p->next=b;
p=a;
}
return dummy.next;
}
};