Knowee
Questions
Features
Study Tools

Write a method to rotate the doubly-linked list

Question

Write a method to rotate the doubly-linked list

🧐 Not the exact question you are looking for?Go ask a question

Solution

Claro, aquí tienes un método para rotar una lista doblemente enlazada:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        last = self.head
        while last.next:
            last = last.next
        last.next = new_node
        new_node.prev = last

    def rotate(self, n):
        if n == 0 or not self.head:
            return

        current = self.head
        count = 1

        while count < n and current:
            current = current.next
            count += 1

        if not current:
            return

        nth_node = current

        while current.next:
            current = current.next

        current.next = self.head
        self.head.prev = current
        self.head = nth_node.next
        self.head.prev = None
        nth_node.next = None

    def print_list(self):
        current = self.head
        while current:
            print(current.data, end=" ")
            current = current.next
        print()

# Ejemplo de uso
dll = DoublyLinkedList()
dll.append(1)
dll.append(2)
dll.append(3)
dll.append(4)
dll.append(5)

print("Lista original:")
dll.print_list()

dll.rotate(2)

print("Lista después de rotar 2 posiciones:")
dll.print_list()

Este código define una clase Node para los nodos de la lista doblemente enlazada y una clase DoublyLinkedList para manejar la lista. El método rotate rota la lista en n posiciones. El método print_list imprime la lista para verificar los resultados.

This problem has been solved

Similar Questions

In a doubly linked list, what are possible directions to traverse it?

Which of the following is a correct method to reverse a doubly linked list?Swap the next and prev pointers of all nodes.Replace all nodes with their corresponding mirror nodes.Swap the data of all nodes.Create a new list and copy nodes in reverse order.

Rotating a linked list by some places clockwise will take a time complexity of?*2 pointsO(1)O(n)O(n^2)None of the above

public ListNode rotateRight(ListNode head, int k) { ListNode slow = head; ListNode fast = head; for(int i=0; i<k;i++){ fast=fast.next; }

Doubly-linked list allows traversing in both the forward and backward directions, it is also called..................a)one-way listb)None of the mentionedc)two-way listd)multi-way list

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.