두 개의 연결 리스트가 동일한지 확인해야 하는 경우 연결 리스트에 요소를 추가하는 방법과 연결 목록에 있는 요소의 동일성을 확인하는 방법이 정의되어 있습니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_structure:
def __init__(self):
self.head = None
self.last_node = None
def add_vals(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def check_equality(list_1, list_2):
curr_1 = list_1.head
curr_2 = list_2.head
while (curr_1 and curr_2):
if curr_1.data != curr_2.data:
return False
curr_1 = curr_1.next
curr_2 = curr_2.next
if curr_1 is None and curr_2 is None:
return True
else:
return False
my_linked_list_1 = LinkedList_structure()
my_linked_list_2 = LinkedList_structure()
my_list = input('Enter the elements of the first linked list: ').split()
for elem in my_list:
my_linked_list_1.add_vals(int(elem))
my_list = input('Enter the elements of the second linked list: ').split()
for elem in my_list:
my_linked_list_2.add_vals(int(elem))
if check_equality(my_linked_list_1, my_linked_list_2):
print('The two linked lists are the same')
else:
print('The two linked list are not same') 출력
Enter the elements of the first linked list: 34 56 89 12 45 Enter the elements of the second linked list: 57 23 78 0 2 The two linked list are not same
설명
-
'Node' 클래스가 생성됩니다.
-
필수 속성이 있는 또 다른 'LinkedList_structure' 클래스가 생성됩니다.
-
첫 번째 요소, 즉 'head'를 'None'으로, 'last_node'를 'None'으로 초기화하는 데 사용되는 'init' 기능이 있습니다.
-
스택에 값을 추가하는 데 도움이 되는 'add_vals'라는 메서드가 정의되어 있습니다.
-
'check_equality'라는 또 다른 메서드가 정의되어 두 연결 목록의 요소가 동일한지 여부를 확인하는 데 도움이 됩니다.
-
같음에 따라 True 또는 False를 반환합니다.
-
'LinkedList_structure'의 인스턴스 2개가 생성됩니다.
-
두 개의 연결 목록에 요소가 추가됩니다.
-
이 두 연결 리스트에서 'check_equality' 메소드가 호출됩니다.
-
출력은 콘솔에 표시됩니다.