leetcode 132: Swap Nodes in Pairs

Swap Nodes in Pairs

Total Accepted: 2897 Total Submissions: 9308

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.


/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        if(head==NULL || head->next==NULL)return head;
        
        ListNode ** pre = &head;
        ListNode* p = head;
        ListNode* q = head->next;
        
        while(q!=NULL) {
            p->next = q->next;
            q->next = p;
            *pre = q;
            
            if(p->next==NULL || p->next->next==NULL) return head;
            pre = &(p->next);
            q=p->next->next;
            p=p->next;
        }
        
        return head;
    }
};


你可能感兴趣的:(leetcode 132: Swap Nodes in Pairs)