zoukankan      html  css  js  c++  java
  • 链表 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

  • 相关阅读:
    vue 前端框架 (二) 表格增加搜索
    vue 前端框架
    数据结构-树的基本操作
    linux的串口驱动分析
    TTY驱动程序架构
    linux MTD系统解析(转)
    DM9000网卡的基本工作原理
    ok6410的LCD裸机范例
    ok6410的DMA裸机总结
    ok6410串口裸机总结
  • 原文地址:https://www.cnblogs.com/luoyinjie/p/11696042.html
Copyright © 2011-2022 走看看