Python程序:旋转双向链表N个节点
当需要将双向链表旋转特定数量的节点时,需要创建一个“Node”类。在这个类中,有三个属性:节点中存在的数据、对链表下一个节点的访问以及对链表上一个节点的访问。
以下是相同的演示 -
示例
class Node:
def __init__(self, my_data):
self.previous = None
self.data = my_data
self.next = None
class double_list:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def add_data(self, my_data):
new_node = Node(my_data)
if(self.head == None):
self.head = self.tail = new_node
self.head.previous = None
self.tail.next = None
else:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
self.tail.next = None
self.size = self.size + 1;
def print_it(self):
curr = self.head
if (self.head == None):
print("The list is empty")
return
print("The nodes in the doubly linked list are :")
while curr != None:
print(curr.data)
curr = curr.next
def rotate_list(self, num):
curr = self.head;
if(num == 0 or num >= self.size):
return;
else:
for i in range(1, num):
curr = curr.next;
self.tail.next = self.head;
self.head = curr.next;
self.head.previous = None;
self.tail = curr;
self.tail.next = None;
my_instance = double_list()
print("Elements are being added to the doubly linked list")
my_instance.add_data(10)
my_instance.add_data(24)
my_instance.add_data(54)
my_instance.add_data(77)
my_instance.add_data(24)
my_instance.add_data(0)
my_instance.print_it()
print("The elements in the list after rotating : ")
my_instance.rotate_list(4)
my_instance.print_it()输出
Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 24 0 The elements in the list after rotating : The nodes in the doubly linked list are : 24 0 10 24 54 77
解释
- 创建了“Node”类。
- 创建了另一个具有所需属性的类。
- 定义了另一个名为“add_data”的方法,用于将数据添加到循环链表。
- 定义了另一个名为“rotate_list”的方法,它使用特定节点作为枢轴并旋转列表,从而将元素移动到不同的位置。
- 定义了另一个名为“print_it”的方法,用于在控制台上显示链表数据。
- 创建了“double_list”类的对象,并在其上调用方法来添加数据。
- 调用了“rotate_list”方法。
- 它迭代链表中的节点,获取中间索引并开始删除元素。
- 使用“print_it”方法在控制台上显示。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP