//recursive approach ListNode *swapPairs2(ListNode *head) { if (NULL == head || NULL == head->next) return head; ListNode *p = swapPairs2(head->next->next); head->next->next = head; head = head->next; head->next->next = p; return head; }
int main() { int i, n; struct ListNode *head = NULL, *tmphead = NULL, *head1, *head2; for(i = 15 ; i >= 1 ; i--) { head = insert(head, i); tmphead = insert(tmphead, i); } head1 = swapPairs1(head); printf("First function: \n"); while(head1) { printf("%d-->", head1->val); head1 = head1->next; } printf("\n"); printf("Second function: \n"); head2 = swapPairs2(tmphead); while(head2) { printf("%d-->", head2->val); head2 = head2->next; } printf("\n"); return 0; }
ListNode *swapPairs(ListNode* head) { //return swapPairs1(head); return swapPairs2(head); }
/* * Here we have two ways to solve this problem: * 1) keep the list's nodes no change. only swap the data in the list node. * 2) swap the list node physically. */ ListNode *swapPairs(ListNode *head) { if(random()%2){ return swapPairs1(head); } return swapPairs2(head); }