이중 연결 리스트(Doubly Linked List)를 지정한 개수의 노드만큼 회전시켜야 할 때는 먼저 'Node' 클래스를 생성해야 합니다. 이 클래스 안에는 세 가지 속성이 존재합니다. 노드에 저장된 데이터(data), 연결 리스트상 다음 노드에 대한 참조(next), 그리고 이전 노드에 대한 참조(previous)입니다.
아래는 이를 구현한 예제입니다.
예제 코드
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
코드 설명
- 'Node' 클래스가 생성됩니다.
- 필요한 속성(head, tail, size)을 가진 'double_list' 클래스가 함께 정의됩니다.
- 'add_data' 메서드는 새로운 노드를 생성하여 이중 연결 리스트의 끝에 데이터를 추가하는 역할을 합니다.
- 'rotate_list' 메서드는 사용자가 지정한 번호의 노드를 기준점(pivot)으로 삼아 리스트 전체를 회전시키고, 그 결과 각 요소들이 새로운 위치로 이동하게 됩니다.
- 'print_it' 메서드는 연결 리스트에 저장된 데이터를 콘솔 화면에 출력하는 기능을 담당합니다.
- 'double_list' 클래스의 객체가 생성되며, 이 객체를 통해 데이터를 추가하는 메서드들이 호출됩니다.
- 회전을 수행하기 위해 'rotate_list' 메서드가 호출됩니다. 이 메서드는 연결 리스트의 노드들을 순회하면서 기준이 되는 위치로 이동한 뒤, head와 tail의 참조를 재설정하여 리스트를 회전시킵니다.
- 마지막으로 'print_it' 메서드를 통해 회전된 결과가 콘솔에 출력됩니다.