链表 123456 变为 321654

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void getMiddleTail(ListNode* head,ListNode* &middle,ListNode*& tail) {
        if(head==NULL || head->next==NULL)
            return ;
        ListNode* slow = head;
        ListNode* fast = head;
        while(1){
            slow = slow->next;
            for(int i=0;i!=2;++i){
                if(fast->next == NULL){
                    middle = slow;
                    tail   = fast;
                    return;
                }
                fast = fast->next;
            }
        }
    }
    
    ListNode * reverse( ListNode* head ){
        if(head==NULL||head->next==NULL)
            return head;
        ListNode * p = head;
        ListNode * mhead = head;
        ListNode * q = head->next;
        while(p->next!=head){
            ListNode * r = q->next;
            p->next = r;
            q->next = mhead;
            mhead   = q;
            q = p->next;
        }
        p->next = NULL;
        return mhead;
    }
    
    ListNode* swapPairs(ListNode* head) {
        if(head==NULL || head->next==NULL)
            return head;
        ListNode * middle , *tail;
        
        getMiddleTail(head,middle,tail);
        
        tail->next = head;
        
        return reverse(middle);

    }
};

1. 先获取middle 4 和tail 6

2. tail 指向head, 那么middle开头的链表变为  456123

3. 翻转middle   321654

原文地址:https://www.cnblogs.com/luoyinjie/p/11696042.html