Tap here to switch tabs
Problem
Submissions
Solution

Solution: Reverse Nodes in k-Group

Statement

Naive approach

A naive approach would be to use another data structure—like a stack—to reverse the nodes of the linked list and then create a new linked list with reversed nodes. Here’s how the algorithm works:

  • We iterate the linked list.

  • We push the kk group of nodes to the stack.

  • We pop all kk numbers of nodes from the stack and add the nodes to a new linked list. When we do this, the stack will give us the reversed nodes in the kk group.

  • We repeat the above steps for every group of size kk present in our linked list.

  • In the end, if there are less than kk nodes left in the original linked list, we’ll point the tail of the reversed linked list to the ...

⋮
Tap here to switch tabs
Problem
Submissions
Solution

Solution: Reverse Nodes in k-Group

Statement

Naive approach

A naive approach would be to use another data structure—like a stack—to reverse the nodes of the linked list and then create a new linked list with reversed nodes. Here’s how the algorithm works:

  • We iterate the linked list.

  • We push the kk group of nodes to the stack.

  • We pop all kk numbers of nodes from the stack and add the nodes to a new linked list. When we do this, the stack will give us the reversed nodes in the kk group.

  • We repeat the above steps for every group of size kk present in our linked list.

  • In the end, if there are less than kk nodes left in the original linked list, we’ll point the tail of the reversed linked list to the ...