0

was trying out this LeetCode question

https://leetcode.com/problems/reverse-nodes-in-k-group/

enter image description here

The output supposed to be [3,2,1,4,5] but I keep on getting [3,2,1,4]. I believe there's problem with my current pointer but couldn't think stop it from referring to head.

I'm new to C++ by the way. Any assistance would be greatly appreciated.

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        // head = [1,2,3,4,5]
        k = 3;
        cout << "RECURSE" << endl;
        ListNode* current = head;
        ListNode* next = NULL;
        ListNode* prev = NULL;
        for(int i = 0; i < k; i++){
            if(head == NULL){
                return current;
            }else{
                next = head->next;
                head->next = prev;
                
                prev = head;
                head = next;
            }
        }
        
        current->next = reverseKGroup(head, k);
        return prev;
    }
};
Danzeeeee
  • 2,588
  • 2
  • 16
  • 18
  • the dupe is language-agnostic, though second top answer addresses C++ specifically in details – 463035818_is_not_an_ai May 12 '21 at 11:28
  • 1
    Sites like leetcode.com are not designed for those who are "new to C++ ". They assume that you are already a C++ expert, and contain a bunch of puzzles that are based on programming or mathematical tricks. Once someone's a C++ expert, then they can compete against others on leetcode.com, and similar puzzle sites. Until then, the best resource for learning C++ is a good C++ textbook. – Sam Varshavchik May 12 '21 at 12:59

0 Answers0