zoukankan      html  css  js  c++  java
  • 每K个节点翻转

        ListNode* ReverseList(ListNode* head, ListNode* tail)
        {
            ListNode* pre = NULL;
            ListNode* next = NULL;
            while (head != tail)
            {
                next = head->next;
                head->next = pre;
                pre = head;
                head = next;
            }
    
            return pre;
        }
    
        ListNode* reverseKGroup(ListNode* head, int k)
        {
            if (head == NULL || head->next == NULL) 
            {
                return head;
            }
    
            ListNode* tail = head;
            for (int i = 0; i < k; i++) 
            {
                //剩余数量小于k的话,则不需要反转。
                if (tail == NULL)
                {
                    return head;
                }
                tail = tail->next;
            }
    
            // 反转前 k 个元素
            ListNode* newHead = ReverseList(head, tail);
            //下一轮的开始的地方就是tail
            head->next = reverseKGroup(tail, k);
    
            return newHead;
        }
    struct ListNode
    {
        int val;
        struct ListNode *next;
        ListNode(int x):val(x), next(NULL) 
        {
        }
    };
    青青园中葵,朝露待日晞。 阳春布德泽,万物生光辉。 常恐秋节至,焜黄华叶衰。 百川东到海,何时复西归? 少壮不努力,老大徒伤悲!
  • 相关阅读:
    redis-单线程为什么快
    redis-数据结构
    http-状态码
    事件绑定完整版2016/4/21
    焦点事件2016、4、21
    ++
    Bom2016/4/21
    添加以及删除className
    getByClassName2016/4/21
    动态添加
  • 原文地址:https://www.cnblogs.com/weiyouqing/p/14513621.html
Copyright © 2011-2022 走看看