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

    Two problems: 

    1. Counting the length is much easier than reversing the last less than k nodes. 

    2.  Don't forget:

    lastGroupTail->next = p;
    
    
    
    
    
    
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
     public:
      ListNode *reverseKGroup(ListNode *head, int k) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (k <= 1 || head == NULL)
          return head;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode *p = head, *last = NULL, *next = NULL, *lastGroupTail = dummy, *curGroupTail = NULL, *res = NULL;
        int count = 1, len = 0;
        for(p = head; p != NULL; p = p->next, ++len);
        p = head;
        int countmax = len / k * k;
        while (p != NULL && count <= countmax) {
          next = p->next;
          if (count % k == 1)
            curGroupTail = p;
          else if (count % k == 0) {
            lastGroupTail->next = p;
            lastGroupTail = curGroupTail;
          }
          p->next = last;
          ++count;
          last = p;
          p = next;
        }
        lastGroupTail->next = p;
        res = dummy->next;
        return res;
      }
    };


  • 相关阅读:
    -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HOME environment variable and mvn script match.chan
    failed to export application
    IOS InHouse 发布流程
    BoneCP学习笔记
    form表单, css1
    HTTP协议, HTML
    自定义ORM框架
    数据库5
    数据库4
    数据库3
  • 原文地址:https://www.cnblogs.com/pangblog/p/3400183.html
Copyright © 2011-2022 走看看