-
-
Save TheSithPadawan/7f0bde8fbfabfca81a32538dc2528893 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static ListNode *reverse(ListNode *head, int k) { | |
// TODO: Write your code here | |
ListNode * dummy = new ListNode(-1); | |
dummy->next = head; | |
ListNode * prev = dummy; | |
ListNode * cur = head; | |
ListNode * last_node_of_prev_list = prev; | |
ListNode * last_node_of_cur_list = cur; | |
while (cur) { | |
int i = 0; | |
// reverse linked list | |
while (cur && i < k) { | |
ListNode* nextnode = cur->next; | |
cur->next = prev; | |
prev = cur; | |
cur = nextnode; | |
i++; | |
} | |
// reset pointers | |
last_node_of_prev_list->next = prev; | |
last_node_of_cur_list->next = cur; | |
// update pointers | |
last_node_of_prev_list = last_node_of_cur_list; | |
last_node_of_cur_list = cur; | |
} | |
return dummy->next; | |
} | |
}; | |
int main(int argc, char *argv[]) { | |
ListNode *head = new ListNode(1); | |
head->next = new ListNode(2); | |
head->next->next = new ListNode(3); | |
head->next->next->next = new ListNode(4); | |
head->next->next->next->next = new ListNode(5); | |
head->next->next->next->next->next = new ListNode(6); | |
head->next->next->next->next->next->next = new ListNode(7); | |
head->next->next->next->next->next->next->next = new ListNode(8); | |
ListNode *result = ReverseEveryKElements::reverse(head, 3); | |
cout << "Nodes of the reversed LinkedList are: "; | |
while (result != nullptr) { | |
cout << result->value << " "; | |
result = result->next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment