Python 程序在循环链表的开头插入新节点
当需要在循环链表的开头插入一个新节点时,需要创建一个“Node”类。在这个类中,有两个属性,节点中存在的数据,以及对链表下一个节点的访问。
在循环链表中,头节点和尾节点彼此相邻。它们连接形成一个圆圈,并且最后一个节点没有“NULL”值。
需要创建另一个类,该类将具有初始化函数,并且节点的头将初始化为“None”。
用户定义了多个方法来在链表的开头添加节点,以及打印节点值。
以下是相同内容的演示 -
示例
class Node:
def __init__(self,data):
self.data = data
self.next = None
class list_creation:
def __init__(self):
self.head = Node(None)
self.tail = Node(None)
self.head.next = self.tail
self.tail.next = self.head
def add_at_beginning(self,my_data):
new_node = Node(my_data);
if self.head.data is None:
self.head = new_node;
self.tail = new_node;
new_node.next = self.head;
else:
temp = self.head;
new_node.next = temp;
self.head = new_node;
self.tail.next = self.head;
def print_it(self):
curr = self.head;
if self.head is None:
print("The list is empty");
return;
else:
print(curr.data),
while(curr.next != self.head):
curr = curr.next;
print(curr.data),
print("\n");
class circular_linked_list:
my_cl = list_creation()
print("Values are being added to the list")
my_cl.add_at_beginning(21);
my_cl.print_it();
my_cl.add_at_beginning(53);
my_cl.print_it();
my_cl.add_at_beginning(76);
my_cl.print_it(); 输出
Values are being added to the list 21 53 21 76 53 21
解释
- 创建“Node”类。
- 创建另一个具有所需属性的类。
- 定义另一个名为“add_at_beginning”的方法,用于在开头(即“head”节点之前)将数据添加到循环链表。
- 定义另一个名为“print_it”的方法,用于显示循环链表的节点。
- 创建“list_creation”类的对象,并在其上调用方法以添加数据。
- 定义一个“init”方法,将循环链表的第一个和最后一个节点设置为None。
- 调用“add_at_beginning”方法。
- 它获取链表的头,在它之前添加一个元素,并将它的地址引用到尾指针和下一个指针。
- 使用“print_it”方法在控制台上显示。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP