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

이중 연결 목록에서 요소를 검색하는 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' 메소드를 사용하여 콘솔에 표시됩니다.