leetcode 24

链表操作的,要注意标记头结点和边界问题。

代码如下:

 1 ListNode *swapPairs(ListNode *head) {  
 2         if(head==NULL||head->next==NULL)  
 3             return head;  
 4         ListNode* p=head;  
 5         ListNode* q=head->next;  
 6         ListNode* x=head->next->next;  
 7         ListNode* t=NULL;  
 8         head=q;  
 9         while(p!=NULL&&q!=NULL){  
10             q->next=p;  
11             p->next=NULL;  
12             if(t!=NULL)  
13                 t->next=q;  
14             t=p;  
15               
16             p=x;  
17             if(x!=NULL)  
18                 q=x->next;  
19             if(q!=NULL)  
20                 x=q->next;  
21   
22         }  
23         if(p!=NULL)  
24             t->next=p;  
25         return head;  
26 }  

更加巧妙的解法,直接对链表中节点的val进行交换,不用操作链表;

代码如下:

 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         int n;  
13         ListNode* node = head;  
14         while (head != NULL && head->next != NULL) {  
15             n = head->val;  
16             head->val = head->next->val;  
17             head->next->val = n;  
18             head = head->next->next;  
19         }  
20         return node; 
21     }
22 };
原文地址:https://www.cnblogs.com/shellfishsplace/p/5847378.html