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.