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;
      }
    };


  • 相关阅读:
    超媒体
    超文本
    视频文件格式
    web.py 模板错误记录
    pip常用记录
    微信公众号绑定服务器 Flask版
    scrapy 简单防封
    python 手写队列
    jQuery个人总结
    PHP用url传递数组
  • 原文地址:https://www.cnblogs.com/pangblog/p/3400183.html
Copyright © 2011-2022 走看看