Swap Nodes in Pairs

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.

Subscribe to see which companies asked this question

/**
 * 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 (NULL == head || NULL == head->next) {
            return head;
        }
        //模拟头结点,方便计算
        ListNode fake(0);
        ListNode* node = &fake;
        node->next = head;
        //从头结点开始进行翻转
        while (node && node->next) {
            node->next =  swap(node->next);
            node = node->next->next;
        }
        return fake.next;
    }
    //返回翻转之后的头结点
    ListNode* swap(ListNode* p) {
        ListNode* q = p->next;
        if (NULL == q) {
            return p;
        }
        ListNode* tmp = q->next;
        q->next = p;
        p->next = tmp;
        return q;
    }

};
原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5119747.html