zoukankan      html  css  js  c++  java
  • Leetcode Reverse Nodes in k-Group

    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

    If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

    You may not alter the values in the nodes, only nodes itself may be changed.

    Only constant memory is allowed.

    For example,
    Given this linked list: 1->2->3->4->5

    For k = 2, you should return: 2->1->4->3->5

    For k = 3, you should return: 3->2->1->4->5

    基本思路就是每经过k个节点就反转一次即可

    class Solution {
    public:
        ListNode *reverse(ListNode* head, ListNode* tail){
            ListNode *newHead = NULL,*p = head;
            while(p!=tail){
                ListNode* tmp = p->next;
                p->next = newHead;
                newHead = p;
                p = tmp;
            }
            return newHead;
        }
        ListNode *reverseKGroup(ListNode *head, int k) {
            ListNode* newHead = new ListNode(0),*newPre = newHead;
            newHead->next = head;
            ListNode* p = head,*pre = head;
            int cnt = 0;
            while(p){
                cnt++;
                ListNode *tmp = p->next;
                if(cnt == k){
                    newPre->next = reverse(pre,p->next);
                    newPre = pre;
                    pre = tmp;
                    cnt = 0;
                }
                p = tmp;
            }
            newPre->next = pre;
            return newHead->next;
        }
    };
  • 相关阅读:
    [bzoj1096][ZJOI2007]仓库建设
    [bzoj1010][HNOI2008]玩具装箱
    [bzoj2301][HAOI2011]Problem b
    [HDU1695]GCD
    [SDOI2006] 保安站岗
    [TJOI2007] 调整队形
    Luogu_1944 最长括号匹配
    [USACO07NOV] Milking Time
    [USACO13FEB] Tractor
    [模板] 一些要复习的模板
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3823275.html
Copyright © 2011-2022 走看看