Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬으로 원형 연결 리스트(Linked List) 요소 정렬하기

원형 연결 리스트(circular linked list)의 요소를 정렬하려면 먼저 'Node' 클래스를 생성해야 합니다. 이 클래스에는 노드에 저장된 데이터(data)와 연결 리스트의 다음 노드를 가리키는 참조(next), 두 가지 속성이 포함됩니다.

원형 연결 리스트에서는 헤드(head)와 꼬리(tail)가 서로 인접해 있습니다. 두 노드가 연결되어 하나의 원을 이루며, 마지막 노드에 'NULL' 값이 존재하지 않는다는 점이 일반 연결 리스트와 다른 특징입니다.

또한 초기화 함수를 포함하는 별도의 'linked_list' 클래스를 만들고, 노드의 헤드를 '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 sort_list(self):
      curr = self.head
      if(self.head == None):
         print("The list is empty")
      else:
         while(True):
            index_val = curr.next
            while(index_val != self.head):
               if(curr.data > index_val.data):
                  temp = curr.data
                  curr.data = index_val.data
                  index_val.data = temp
               index_val = index_val.next
            curr =curr.next
            if(curr.next == self.head):
               break;
   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("The list is being sorted")
   my_cl.sort_list()
   print("The sorted list is : ")
   my_cl.print_it()

실행 결과

Nodes are being added to the list
The list is :
21
54
78
99
27
The list is being sorted
The sorted list is :
21
27
54
78
99

코드 설명

  • 'Node' 클래스가 생성됩니다. 각 노드는 데이터와 다음 노드에 대한 참조를 가집니다.
  • 필요한 속성들을 담고 있는 또 다른 클래스가 생성됩니다.
  • 'sort_list' 메서드가 정의되어 원형 연결 리스트의 요소를 오름차순 또는 내림차순으로 정렬합니다. 여기서는 인접한 노드들의 값을 비교하여 교환하는 버블 정렬(bubble sort) 방식을 사용합니다.
  • 'print_it' 메서드가 정의되어 원형 연결 리스트의 모든 노드 값을 화면에 표시합니다.
  • 'list_creation' 클래스의 객체가 생성되고, 데이터를 추가하기 위해 관련 메서드들이 호출됩니다.
  • 'init' 메서드가 정의되어 원형 연결 리스트의 첫 번째 노드(head)와 마지막 노드(tail)를 None으로 초기화합니다.
  • 'sort_list' 메서드가 호출되면 리스트를 순회하면서 각 요소를 값의 크기에 따라 알맞은 위치에 배치합니다.
  • 정렬된 최종 결과는 'print_it' 메서드를 통해 콘솔에 출력됩니다.

참고 사항

위 예제에서 사용된 버블 정렬 방식은 구현이 간단하지만 시간 복잡도가 O(n²)이므로, 데이터 개수가 많아지면 성능이 저하될 수 있습니다. 대량의 데이터를 다룰 경우에는 병합 정렬과 같은 더 효율적인 알고리즘을 적용하는 것이 좋습니다.