Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

REVERSE NODES IN A LINKED LIST IN K GROUPS #65

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions Linkedlist/reverse k nodes in ll.CPP
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yash-rana23 Please update the code with Problem Statement and Sample Test Case. Code is directly from Leetcode submission. Update the PR so that it can be merged. 👨🏻‍💻

* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode*reverse(ListNode*head, ListNode*tail) {
if (head == tail)
return head;
ListNode * temp = reverse(head->next, tail);
ListNode*loc = head->next;
loc->next = head;

head->next = NULL;
return temp;

}
ListNode* reverseKGroup(ListNode* head, int k) {
if (k == 1)
return head;

ListNode*templ = head;
ListNode*tail = NULL;
int c = 1;
while (templ != NULL) {
int j = k - 1;
ListNode*temp = templ;
while (j && temp->next != NULL) {
temp = temp->next;
j--;

}
if (temp->next == NULL && j > 0) {
tail->next = templ;
cout << 1;
break;
}

ListNode*temp1 = temp->next;
ListNode*temp2 = reverse(templ, temp);
templ = temp1;
ListNode*temp3 = temp2;
while (temp3->next != NULL) {
temp3 = temp3->next;
}
temp3->next = temp1;
if (c != 1) {

tail->next = temp2;
tail = temp3;
}
if (c == 1) {
head = temp2;
}
c++;
tail = temp3;
}
return head;



}
};