LeetCode Swap Nodes in Pairs

note the edge cases!

Easy!

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *swapPairs(ListNode *head) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         
15         if(head==NULL || head->next==NULL)
16             return head;
17         
18         ListNode *p = head;
19         ListNode *q = head->next;
20         
21         // first
22         p->next = q->next;
23         q->next = p;
24         head = q;        
25         
26         // others
27         while(p->next!=NULL && p->next->next!=NULL)
28         {
29             q = p->next->next;
30             p->next->next = q->next;
31             q->next = p->next;
32             p->next = q;
33             p = q->next;
34         }
35         
36         return head;
37     }
38 };
原文地址:https://www.cnblogs.com/CathyGao/p/3057458.html