Leetcode 0025. Reverse Nodes in k-Group

Posted zeroArn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 0025. Reverse Nodes in k-Group相关的知识,希望对你有一定的参考价值。

技术分享
居然把头插法写错了,debug了一个多小时
/**
 * 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) {
        if(k == 1 || head == nullptr)  return head;
        ListNode *tail = head;
        int i;
        for(i=0;i<k && tail != nullptr;i++,tail=tail->next);
        if(i<k) return head;
        tail = reverseKGroup(tail, k);
        ListNode* rear = head,*tmp=nullptr;
        head= tail;
        for(int i = 0;i<k;i++){
              tmp = rear->next;        
              rear->next = head;
              head = rear;
              rear = tmp;
        }
        return head;
    }
};
View Code

 

以上是关于Leetcode 0025. Reverse Nodes in k-Group的主要内容,如果未能解决你的问题,请参考以下文章

leetcode No557. Reverse Words in a String III

leetcode练习之No.7------ 翻转整数reverse_integer

leetcode-easy-others-190. Reverse Bits-NO

[leetcode-557-Reverse Words in a String III]

[LeetCode] No. 9 Palindrome Number

No 206, Reverse Linked List