心得:做链表类题目,多用中间变量,代码的可读性比简洁性更重要,适当注释。在纸上画画图,看看各操作节点的next指针最后都指对了没。
代码:
1 ListNode *swapPairs(ListNode *head) { 2 if (!head) 3 return NULL; 4 5 ListNode *prev = NULL; 6 ListNode *curr = head; 7 ListNode *next = curr->next; 8 head = NULL; 9 10 while (next) { 11 ListNode *nextnext = next->next; 12 if (!head) 13 head = next; 14 else 15 prev->next = next; 16 prev = next->next = curr; 17 prev->next = curr = nextnext; 18 next = nextnext ? nextnext->next : NULL; 19 } 20 21 return head ? head : curr; 22 }