一、问题描述
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) {
if(head == NULL)
return NULL;
ListNode *p = head;
ListNode *q = head -> next;
while(q){
int temp = p -> val;
p -> val = q->val;
q->val = temp;
if(q -> next == NULL)
break;
if(q -> next -> next != NULL){
p = q -> next;
q = p -> next;
}else
break;
}
return head;
}
};