题意:链表两两之间交换位置。
思路:简单模拟。
/**
* 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) return head;
if(head->next == NULL) return head;
ListNode* myhead = new ListNode(0);
myhead->next = head;
ListNode* next = myhead;
while(next && next->next && next->next->next) {
ListNode* temp1 = next->next;
ListNode* temp2 = next->next->next;
next->next = temp2;
temp1->next = temp2->next;
temp2->next = temp1;
next = temp1;
}
return myhead->next;
}
};