원형 연결 리스트(circular linked list)에서 특정 요소를 검색하려면 먼저 'Node' 클래스를 생성해야 합니다. 이 클래스에는 두 가지 속성이 있는데, 하나는 노드에 저장된 데이터(data)이고, 다른 하나는 연결 리스트의 다음 노드를 가리키는 참조(next)입니다.
원형 연결 리스트의 구조
원형 연결 리스트에서는 헤드(head)와 꼬리(tail)가 서로 인접해 있으며, 두 노드가 연결되어 하나의 원(circle)을 이룹니다. 따라서 마지막 노드에는 일반 연결 리스트와 달리 '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
코드 동작 설명
- 'Node' 클래스가 생성됩니다.
- 필요한 속성들을 가진 또 다른 클래스가 생성됩니다.
- 'search_value'라는 이름의 메서드가 정의되어, 연결 리스트에서 특정 요소를 검색하는 데 사용됩니다.
- 'print_it'이라는 이름의 메서드가 정의되어, 원형 연결 리스트의 노드 값들을 화면에 출력합니다.
- 'list_creation' 클래스의 객체가 생성되고, 데이터를 추가하기 위해 해당 메서드들이 호출됩니다.
- 'init' 메서드가 정의되어, 원형 연결 리스트의 첫 번째 노드와 마지막 노드를 None으로 초기화합니다.
- 'search_value' 메서드가 호출되면 리스트를 처음부터 순회하면서 찾고자 하는 요소가 존재하는지 확인합니다.
- 요소를 찾으면 해당 요소의 위치(인덱스)가 출력됩니다.
- 모든 결과는 'print_it' 메서드를 통해 콘솔에 표시됩니다.