Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Rotate given linked list clockwise

What is clockwise rotation of linked list.

k is a rotation key. that means moving first (k) nodes to end of linked list. (k) is positive number and it is possible this (k) rotation key are greater than number of linked list nodes.

Example 1:

Given input

1-->2-->3-->4-->5-->6-->7-->8-->NULL

k=3 (k rotation key)

After rotate

4-->5-->6-->7-->8-->1-->2-->3-->NULL

Example 2:

Given input

1-->2-->3-->4-->5-->6-->7-->8-->NULL

k=6 (k rotation key)

After rotate

7-->8-->1-->2-->3-->4-->5-->6--->NULL

Example 3:

Given linked list.

1-->2-->3-->4-->5-->6-->7-->8-->NULL

k=26 (k rotation key)

After rotate

3-->4-->5-->6-->7-->8-->1-->2-->NULL

Expalian

how to get this result. let discuss about this rotation. now linked list are 8 nodes. moving first node to end position.

View Rotation:

Rotation no 1

First node move to end position.

2-->3-->4-->5-->6-->7-->8-->1-->NULL

Roation no 2

3-->4-->5-->6-->7-->8-->1-->2-->NULL

Roation no 3

4-->5-->6-->7-->8-->1-->2-->3-->NULL

Roation no 4

5-->6-->7-->8-->1-->2-->3-->4-->NULL

Roation no 5

6-->7-->8-->1-->2-->3-->4-->5-->NULL

Roation no 6

7-->8-->1-->2-->3-->4-->5-->6-->NULL

Roation no 7

8-->1-->2-->3-->4-->5-->6-->7-->NULL

Roation no 8

1-->2-->3-->4-->5-->6-->7-->8-->NULL

After 8 rotation

Look at this linked list. initial linked list and after rotated linked list are same. continue this step 26 time.

Roation no 26

3-->4-->5-->6-->7-->8-->1-->2-->NULL

Ratate list linked

Given K=5.

root_ptr87654321

Another example [k=3]

root_ptr87654321

Algorithm:

Code execution:

When k=3

Stack Areamainroot(pointer)show_datatemp(pointer) NULL Heap Areastruct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 3next (pointer)= NULLstruct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 5next (pointer) struct Nodedata (int)= 6next (pointer) struct Nodedata (int)= 7next (pointer) struct Nodedata (int)= 8next (pointer)

Note that not given all step of execution process here.View How to insert linked list element and so on.

Try it yourself

C program to Rotate linked list node.

OutPut:

Spread the post

Recommended Posts: