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

N 노드로 이중 연결 목록을 회전하는 Python 프로그램

<시간/>

이중 연결 리스트를 특정 노드만큼 회전시켜야 하는 경우에는 'Node' 클래스를 생성해야 합니다. 이 클래스에는 노드에 있는 데이터, 연결 목록의 다음 노드에 대한 액세스, 연결 목록의 이전 노드에 대한 액세스의 세 가지 속성이 있습니다.

아래는 동일한 데모입니다 -

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
      self.size = 0
   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
         self.size = self.size + 1;
   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 rotate_list(self, num):
      curr = self.head;
      if(num == 0 or num >= self.size):
         return;
      else:
         for i in range(1, num):
            curr = curr.next;
         self.tail.next = self.head;
         self.head = curr.next;
         self.head.previous = None;
         self.tail = curr;
         self.tail.next = None;
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 elements in the list after rotating : ")
my_instance.rotate_list(4)
my_instance.print_it()

출력

Elements are being added to the doubly linked list
The nodes in the doubly linked list are :
10
24
54
77
24
0
The elements in the list after rotating :
The nodes in the doubly linked list are :
24
0
10
24
54
77

설명

  • '노드' 클래스가 생성됩니다.
  • 필수 속성이 있는 다른 클래스가 생성됩니다.
  • 순환 연결 목록에 데이터를 추가하는 데 사용되는 'add_data'라는 또 다른 메서드가 정의되어 있습니다.
  • 특정 노드를 피벗으로 사용하고 목록을 회전하여 요소를 다른 위치로 이동하는 'rotate_list'라는 또 다른 메서드가 정의되어 있습니다.
  • 연결 목록 데이터를 콘솔에 표시하는 데 사용되는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
  • 'double_list' 클래스의 객체가 생성되고 이에 대한 메소드가 호출되어 데이터를 추가합니다.
  • 'rotate_list' 메소드가 호출됩니다.
  • 연결된 목록의 노드를 반복하고 가장 가운데에 있는 인덱스를 가져와 요소를 삭제하기 시작합니다.
  • 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.