1. 程式人生 > >LeetCode24. Swap Nodes in Pairs(C++)

LeetCode24. Swap Nodes in Pairs(C++)

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

Example:

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

Note:

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

題目大意:兩兩交換節點

/**
 * 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,*q;
        p=head;
        if(p==NULL)
            return head;
        q=head->next;
        if(q==NULL)
            return head;
        while(q!=NULL&&q->next!=NULL){
            int temp=p->val;
            p->val=q->val;
            q->val=temp;
            p=p->next->next;
            q=q->next->next;
        }
        if(p!=NULL&&q!=NULL){
            int temp=p->val;
            p->val=q->val;
            q->val=temp;
        }
        return head;
    }
};

另:直接交換節點的值也是可以的

/**
 * 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) {
        if(head==NULL)
            return head;
        ListNode *p,*q;
        p=head,q=head->next;
        while(q!=NULL){
            swap(p->val,q->val);
            p=q->next;
            if(p==NULL)
                break;
            q=p->next;
        }
        return head;
    }
};