Python程序搜索双向链表中的元素


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

需要创建另一个类,该类将具有初始化函数,并且节点的头部将在其中初始化为“None”。

用户定义了多个方法来向链表添加节点,显示节点以及在链表中搜索特定节点。

在双向链表中,节点具有指针。当前节点将具有指向下一个节点和前一个节点的指针。列表中的最后一个值将在下一个指针中具有“NULL”值。它可以双向遍历。

以下是相同内容的演示 -

示例

 在线演示

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
   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
   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 search_node(self, val_to_search):
      i = 1;
      flag_val = False;
      curr = self.head;
      if(self.head == None):
         print("List is empty")
         return
      while(curr != None):
         if(curr.data == val_to_search):
            flag_val = True
            break
         curr = curr.next
         i = i + 1
      if(flag_val):
         print("The node is present in the list at position : ")
         print(i)
      else:
         print("The node isn't present in the list")
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 element 77 is being searched... ")
my_instance.search_node(77)
print("The element 7 is being searched... ")
my_instance.search_node(7)

输出

Elements are being added to the doubly linked list
The nodes in the doubly linked list are :
10
24
54
77
24
0
The element 77 is being searched...
The node is present in the list at position :
4
The element 7 is being searched...
The node isn't present in the list

解释

  • 创建“节点”类。
  • 创建另一个具有所需属性的类。
  • 定义另一个名为“add_data”的方法,用于向循环链表添加数据。
  • 定义另一个名为“search_node”的方法,该方法接受一个需要在双向链表中搜索的参数。
  • 它搜索元素并返回索引
  • 定义另一个名为“print_it”的方法,用于在控制台上显示链表数据。
  • 创建“double_list”类的对象,并在其上调用方法以添加数据。
  • 调用“search_node”方法。
  • 它遍历链表中的节点,如果找到则给出元素的索引。
  • 使用“print_it”方法在控制台上显示此内容。

更新于: 2021年3月11日

459 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.