24:Swap Nodes in Pairs【链表】

题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/

/*题意:将链表相邻的两两结点交换*/

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        ListNode *pre = NULL;
        ListNode *Next = head;

        while(Next && Next->next) {
            ListNode *first = Next;
            ListNode *second = Next->next;
            Next = second->next;
            if(pre) {
                pre->next = second;
                second->next = first;
                first->next = Next;
                pre = first;
            }
            else {
                head = second;
                second->next = first;
                first->next = Next;
                pre = first;
            }
        }
        return head;
    }
};

  

posted @ 2015-05-20 17:05  天丶下  阅读(131)  评论(0编辑  收藏  举报