/* Druver program to test above function */ int main() { struct node *start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ // push(&start, 7); // push(&start, 6); // push(&start, 5); // push(&start, 4); // push(&start, 3); push(&start, 2); push(&start, 1); printf("\n Linked list before calling pairWiseSwap() "); printList(start); pairWiseSwap(&start); printf("\n Linked list after calling pairWiseSwap() "); printList(start); getchar(); return 0; }
struct node *pairWiseSwap(struct node* head) { if (head == NULL || head->next == NULL) return head; struct node* remaing = head->next->next; struct node* newhead = head->next; newhead->next = head; head->next = pairWiseSwap(remaing); return newhead; }
//方法二: 递归 void pairWiseSwap(struct node *head) { if (NULL == head || NULL == head->next) { return ; } head->data ^= head->next->data; head->next->data ^= head->data; head->data ^= head->next->data; pairWiseSwap(head->next->next); }
int main() { struct node *start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf("\n Linked list before calling pairWiseSwap() "); printList(start); start = pairWiseSwap(start); // NOTE THIS CHANGE printf("\n Linked list after calling pairWiseSwap() "); printList(start); return 0; }