Python循环链表元素搜索程序


当需要在循环链表中搜索元素时,需要创建一个“节点”类。在这个类中,有两个属性:节点中存在的数据,以及对链表中下一个节点的访问。

在循环链表中,表头和表尾彼此相邻。它们连接形成一个环,最后一个节点没有“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_data(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:
         self.tail.next = new_node
         self.tail = new_node
         self.tail.next = self.head
   def search_value(self,elem_to_search):
      curr = self.head;
      i = 1;
      flag_val = False;
      if(self.head == None):
         print("The list is empty");
      else:
         while(True):
            if(curr.data == elem_to_search):
               flag_val = True;
               break;
            curr = curr.next;
            i = i + 1;
            if(curr == self.head):
               break;
         if(flag_val):
            print("The element is present in list at position : " + str(i));
         else:
            print("The element is not present in list");
   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("Nodes are being added to the list")
   my_cl.add_data(21)
   my_cl.add_data(54)
   my_cl.add_data(78)
   my_cl.add_data(99)
   my_cl.add_data(27)
   print("The list is :")
   my_cl.print_it()
   print("Value 99 is being searched")
   my_cl.search_value(99)
   print("Value 0 is being searched")
   my_cl.search_value(0)

输出

Nodes are being added to the list
The list is :
21
54
78
99
27
Value 99 is being searched
The element is present in list at position : 4
Value 0 is being searched
The element is not present in list

解释

  • 创建了“节点”类。
  • 创建了另一个具有所需属性的类。
  • 定义了另一个名为“search_value”的方法,用于在链表中搜索特定元素。
  • 定义了另一个名为“print_it”的方法,用于显示循环链表的节点。
  • 创建了“list_creation”类的对象,并在其上调用方法以添加数据。
  • 定义了一个“init”方法,将循环链表的第一个和最后一个节点设置为None。
  • 调用“search_value”方法。
  • 它遍历列表,并检查是否找到了需要搜索的元素。
  • 如果找到,则显示其索引。
  • 使用“print_it”方法在控制台上显示此信息。

更新于:2021年3月11日

257 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.