很简单的一道链表题,还是错了orz
/**
* 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 NULL;
}
if(head->next == NULL){
return head;
}
ListNode dummy(-1);
dummy.next = head;
ListNode* prev = &dummy, *tmp = head;
while(tmp!= NULL && tmp->next != NULL){
ListNode* pprev = tmp;
ListNode* nnext = tmp->next;
tmp->next = nnext->next;
nnext->next = tmp;
prev->next = nnext;
prev = tmp;
tmp = tmp->next;
}
return dummy.next;
}
};
错误原因:没有对链表长度为奇数or偶数的情况分开考虑。。考虑不够周全。。。