Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program For Reversing A Doubly Linked List
Next article icon

Python3 Program to Rotate Doubly linked list by N nodes

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. 
 


N = 2
Rotated List: 
 


Examples: 
 

Input : a  b  c  d  e   N = 2
Output : c d e a b

Input : a b c d e f g h N = 4
Output : e f g h a b c d


Asked in Amazon 
 


To rotate the Doubly linked list, we need to change next of Nth node to NULL, next of last node to previous head node, and prev of head node to last node and finally change head to (N+1)th node and prev of new head node to NULL (Prev of Head node in doubly linked list is NULL) 
So we need to get hold of three nodes: Nth node, (N+1)th node and last node. Traverse the list from beginning and stop at Nth node. Store pointer to Nth node. We can get (N+1)th node using NthNode->next. Keep traversing till end and store pointer to last node also. Finally, change pointers as stated above and at Last Print Rotated List using 
PrintList Function. 
 

Python3
# Node of a doubly linked list  class Node:      def __init__(self, next = None,                         prev = None, data = None):          self.next = next # reference to next node in DLL          self.prev = prev # reference to previous node in DLL          self.data = data   def push(head, new_data):       new_node = Node(data = new_data)       new_node.next = head      new_node.prev = None      if head is not None:          head.prev = new_node       head = new_node     return head  def printList(head):      node = head      print("Given linked list")     while(node is not None):          print(node.data, end = " "),          last = node          node = node.next      def rotate(start, N):     if N == 0 :         return      # Let us understand the below code      # for example N = 2 and      # list = a <-> b <-> c <-> d <-> e.      current = start       # current will either point to Nth      # or None after this loop. Current      # will point to node 'b' in the      # above example      count = 1     while count < N and current != None :         current = current.next         count += 1      # If current is None, N is greater      # than or equal to count of nodes      # in linked list. Don't change the      # list in this case      if current == None :         return      # current points to Nth node. Store      # it in a variable. NthNode points to      # node 'b' in the above example      NthNode = current       # current will point to last node      # after this loop current will point      # to node 'e' in the above example      while current.next != None :         current = current.next      # Change next of last node to previous      # head. Next of 'e' is now changed to      # node 'a'      current.next = start       # Change prev of Head node to current      # Prev of 'a' is now changed to node 'e'      start.prev = current       # Change head to (N+1)th node      # head is now changed to node 'c'      start = NthNode.next      # Change prev of New Head node to None      # Because Prev of Head Node in Doubly      # linked list is None      start.prev = None      # change next of Nth node to None      # next of 'b' is now None      NthNode.next = None      return start  # Driver Code if __name__ == "__main__":     head = None      head = push(head, 'e')     head = push(head, 'd')     head = push(head, 'c')     head = push(head, 'b')     head = push(head, 'a')      printList(head)     print(" ")          N = 2     head = rotate(head, N)      printList(head)  # This code is contributed by vinayak sharma 

Output
Given linked list  a  b  c  d  e Rotated Linked list  c  d  e  a  b

Time Complexity: O(N) (N is number of linked list’s node)
Auxiliary Space: O(N)

Please refer complete article on Rotate Doubly linked list by N nodes for more details!



Next Article
Python Program For Reversing A Doubly Linked List
author
kartik
Improve
Article Tags :
  • DSA
  • Linked List
  • Python
  • Python Programs
  • Amazon
  • doubly linked list
  • Python-DSA
  • rotation
Practice Tags :
  • Amazon
  • Linked List
  • python

Similar Reads

  • Python3 Program To Rotate Linked List Block Wise
    Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples: Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1Output: 3->1->2-
    3 min read
  • Python Program For Rotating A Linked List
    Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in
    5 min read
  • Python3 Program for Clockwise rotation of Linked List
    Write a Python3 program for a given singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2 Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULLInput: 7 -> 9 -> 11 -> 1
    5 min read
  • Python Program For QuickSort On Doubly Linked List
    Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot. C/C++ Code """A typical recursive implementation of Quicksort for array """ """ This function takes last element as pivot, places the p
    5 min read
  • Python Program For Reversing A Doubly Linked List
    Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example.  (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes
    4 min read
  • Python Program For Merge Sort For Doubly Linked List
    Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
    3 min read
  • Python Program To Delete Alternate Nodes Of A Linked List
    Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
    3 min read
  • Python Program To Find The Sum Of Last N Nodes Of The Given Linked List
    Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 <= n <= number of nodes in the linked list. Examples: Input: 10->6->8->4->12, n = 2 Output: 16 Sum of last two nodes: 12 + 4 = 16 Input: 15->7->9->5->16->14, n = 4
    10 min read
  • Python Program To Delete Middle Of Linked List
    Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
    4 min read
  • Python Program To Delete N Nodes After M Nodes Of A Linked List
    Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.Difficulty Level: Rookie Examples: Input: M = 2, N = 2 Linked List: 1->2->3->4->5->6->7->8 Output: Linked L
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences