Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

这题要求遍历链表,两两交换,也算是一道比较简单的题目,我们只需要拿到需要交换的前驱节点就可以了。直接上代码:

  1. class Solution {
  2. public:
  3. ListNode *swapPairs(ListNode *head) {
  4. if(!head || !head->next) {
  5. return head;
  6. }
  7. ListNode dummy(0);
  8. ListNode* p = &dummy;
  9. dummy.next = head;
  10. while(p && p->next && p->next->next) {
  11. ListNode* n = p->next;
  12. ListNode* nn = p->next->next;
  13. p->next = nn;
  14. n->next = nn->next;
  15. nn->next = n;
  16. p = p->next->next;
  17. }
  18. return dummy.next;
  19. }
  20. };