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

파이썬(Python)으로 순환 연결 리스트의 중복 요소 제거하기

순환 연결 리스트(circular linked list)에서 중복 요소를 제거하려면 먼저 'Node' 클래스를 생성해야 합니다. 이 클래스에는 두 가지 속성이 있습니다. 하나는 노드에 저장된 데이터이고, 다른 하나는 연결 리스트의 다음 노드에 접근하기 위한 참조입니다.


순환 연결 리스트는 head(첫 번째 노드)와 tail(마지막 노드)이 서로 인접하여 원 형태로 연결된 자료구조입니다. 따라서 마지막 노드에는 'NULL' 값이 존재하지 않습니다.


다음으로 초기화 함수를 포함하는 별도의 클래스를 생성해야 하며, 이 클래스 안에서 head를 '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 remove_duplicate_vals(self):  
        curr = self.head
        if(self.head == None):
            print("The list is empty")
        else:
            while(True):
                temp = curr
                index_val = curr.next
                while(index_val != self.head):
                    if(curr.data == index_val.data):
                        temp.next = index_val.next
                    else:
                        temp = index_val
                    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(21)
    print("The list is :")
    my_cl.print_it();  
    my_cl.remove_duplicate_vals()
    print("The updated list is :")
    my_cl.print_it();

출력 결과

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

The updated list is :
21
54
78
99

동작 원리

  • 'Node' 클래스를 생성합니다.
  • 필요한 속성들을 담은 또 다른 클래스를 생성합니다.
  • 'remove_duplicate_vals' 메서드를 정의하여 연결 리스트에 존재하는 중복 요소를 제거합니다.
  • 'print_it' 메서드를 정의하여 순환 연결 리스트의 노드들을 화면에 출력합니다.
  • 'list_creation' 클래스의 객체를 생성하고, 해당 객체의 메서드를 호출하여 데이터를 추가합니다.
  • '__init__' 메서드를 정의하여 순환 연결 리스트의 첫 번째 노드와 마지막 노드를 None으로 초기화합니다.
  • 'remove_duplicate_vals' 메서드를 호출합니다.
  • 메서드는 리스트를 순회하며 반복되는 요소가 있는지 확인합니다.
  • 중복 요소가 발견되면 해당 요소를 삭제합니다.
  • 마지막으로 'print_it' 메서드를 사용해 결과를 콘솔에 출력합니다.

참고로 위 방식은 각 노드에 대해 나머지 노드들을 모두 비교하므로 시간 복잡도가 O(n²)입니다. 데이터 개수가 많다면 해시 집합(set)을 활용해 이미 등장한 값을 기록하는 방식으로 O(n)까지 최적화할 수 있습니다.