reverse a LL after Kth node
Node* reverseAfterK(Node* &head, int k){
// go to kth
Node* temp = head;
for(int i=1;i<k;i++){
temp = temp->next;
}
if(temp->next == NULL || temp->next->next == NULL) return head;
Node* newTail = temp->next;
// reversing
Node* prev = NULL;
Node* cur = temp->next;
Node* nex = temp->next->next;
while(cur){
cur->next = prev;
prev = cur;
cur = nex;
if(nex) nex = nex->next;
}
temp->next = prev;
newTail->next = NULL;
return head;
}

Comments
Post a Comment