Total Accepted: 84322
Total Submissions: 243618
Difficulty: Medium
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
交换链表当中相邻两个节点的值 , 一个指针指向前,另一个指向他的下一个节点,交换即可 ;
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *p ,*q ;
if(!head )
return nullptr ;
p = head ; q = head ->next ;
while ( q && p )
{
swap(p->val , q->val ) ;
p = p -> next ;
if( p )
p = p->next ;
q = q-> next ; // 非空才能往后移动
if (q)
q = q-> next ;
}
return head ;
}
};