t**r 发帖数: 3428 | 1 class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* p = head;
ListNode* prev = dummy;
while(p && p->next){
ListNode* q = p->next;
ListNode* r = p->next->next;
prev->next = q;
q->next = p;
p->next = r;
prev = p;
p = r;
}
return dummy->next;
}
}; |
e*********5 发帖数: 137 | 2 //改进说不上。我自己喜欢用递归,看起来跟简洁。当然,不不知道效率如何。
ListNode *swapPairs(ListNode *head) {
if(!head||!head->next)
return head;
ListNode * first=head, *second=first->next, *temp=second->next;
ListNode * tail=swapPairs(temp);
first->next=tail;
second->next=first;
return second;
} |
l***4 发帖数: 1788 | 3 感谢分享
【在 e*********5 的大作中提到】 : //改进说不上。我自己喜欢用递归,看起来跟简洁。当然,不不知道效率如何。 : ListNode *swapPairs(ListNode *head) { : if(!head||!head->next) : return head; : : ListNode * first=head, *second=first->next, *temp=second->next; : ListNode * tail=swapPairs(temp); : first->next=tail; : second->next=first; :
|