## Posts

Showing posts from May, 2018

### Reversing first k nodes of a Linked List

In this post, we will discuss a method to reverse k nodes from the starting of the linked list. In one of my earlier post, we have already discussed methods to reverse a given linked list. Here We will create a method that accepts the head of the linked list and Number k that indicates the number of elements to be reversed. To do this we will be using a simple method to reverse the linked list with an additional condition in the while loop where decrease k after each iteration. Have a look at my previous post on Linked List in c++ to see how to reverse a linked list.

Let’s directly look at the algorithm and code to understand it better

Algorithm:
In the above code, we use 3 pointers current, previous and next. Initially, the current node points to the head node, the previous and next nodes are Null Then we use a while loop to traverse through the linked list and also decrease k In each iteration, we do the following assign next pointer to current node's link field update current nod…