Java program to rotate doubly linked list by N nodesIn this program, we need to create a doubly linked list and rotate it by n node. This can be achieved by maintaining a pointer that starts from the head node and traverses the list until current points to the nth node. Move the list from head to the nth node and place it after tail. Now nth node will be the tail of the list and node next to nth node will be the new head. Here, n should always be greater than 0 but less than the size of the list. Original List: List after rotating it by 3 nodes: In the above example, we need to rotate list by 3 nodes. First, we iterate through the list until current points to the 3rd node which is, in this case, are node 3. Move the list from node 1 to 3 and place it after tail. Now, node 4 will be new head and node 3 will be the new tail. Algorithm
a. rotateList() will rotate the list by given n nodes.
a. display() will show all the nodes present in the list.
Program:Output: Original List: 1 2 3 4 5 Updated List: 4 5 1 2 3 Next TopicJava Programs |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India