第五天leetcode刷题
解题思路:不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
具体代码实现如下:
/**
* 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* slow=head;
ListNode* fast=head->next;
ListNode* pre=new ListNode(0);
ListNode* ans = pre;
while(slow&&fast){
slow->next = fast->next;
fast->next = slow;
pre->next = fast;
if(slow->next==NULL||slow->next->next==NULL){
break;
}
fast = slow->next->next;
pre = slow;
slow = slow->next;
}
return ans->next;
}
};