Swap Nodes in Pairs

LeetCode #24


Description:

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

Example:

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.

Idea:

用三个pointer,pre, curr, next,用来调整。

Code:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==NULL || head->next==NULL) return head;
        ListNode *curr_ptr=head, *next_ptr=head->next;
        ListNode dummy(-1);
        ListNode * pre_ptr=&dummy;

        while(curr_ptr!=NULL && next_ptr!=NULL){
            pre_ptr->next=next_ptr;
            pre_ptr=curr_ptr;

            curr_ptr->next=next_ptr->next;
            next_ptr->next=curr_ptr;

            curr_ptr=curr_ptr->next;
            if(curr_ptr!=NULL)
                next_ptr=curr_ptr->next;
        }
        return dummy.next;
    }
};

results matching ""

    No results matching ""