Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

순환 연결 목록에서 요소를 검색하는 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' 클래스의 객체가 생성되고 이에 대한 메소드가 호출되어 데이터를 추가합니다.
  • 순환 연결 목록의 첫 번째와 마지막 노드가 None으로 지정되는 '초기화' 메서드가 정의됩니다.
  • 'search_value' 메소드가 호출됩니다.
  • 목록을 반복하고 검색해야 하는 요소가 있는지 확인합니다.
  • 찾으면 색인이 표시됩니다.
  • 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.