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 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告