Skip to main content

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…

Rotate Linked List

In this post, we will discuss a method to Rotate the Linked List in an Anti-clockwise direction. This is one of the easy questions asked in coding interviews. There are a lot of approaches that one can try using for this problem, below algorithm according to me is one of the simpler approaches if not the best. To rotate a linked list we simply need to link the tail node to the head node and move the head pointer to the next node, we repeat this step according to shift value. Let's have a look at below algorithm. We use 2 pointers for this algorithm, current node and tail node, the current node initially points to the head node and will become the new head node after our operations and tail node marks the end of the linked list.


Algorithm:


consider 2 nodes current node and tail node.Initialize current node to point to the head of the Linked ListInitialize tail node to point to the head of the Linked List Move the tail pointer and make tail point the last element Repeat the below step…