24. Swap Nodes in Pairs Posted on 2017-09-03 | Edited on 2018-07-10 | In OJ , LeetCode | 题目https://leetcode.com/problems/swap-nodes-in-pairs/description/ 想法比较简单,虽然没啥意思,但还是做一下 考虑头的变化,以及尾就没有问题了 答案1234567891011121314151617181920212223242526272829/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode *p = head; if (p == NULL || p->next == NULL) return p; p = head; ListNode *q = head->next->next; head = head->next; head->next = p; p->next = q; while(q != NULL && q->next != NULL) { p->next = q->next; ListNode *tmp = q->next->next; q->next = tmp; p = p->next->next; q = q->next; } return head; }};