두 개의 연결 리스트에서 특정 위치의 대응하는 요소를 추가해야 하는 경우, 연결 리스트에 요소를 추가하는 방법, 연결 리스트의 요소를 출력하는 방법, 연결 리스트의 해당 위치에 요소를 추가하는 방법 목록이 정의됩니다. 두 개의 목록 인스턴스가 생성되고 이러한 연결 목록 인스턴스에서 이전에 정의된 메서드가 호출됩니다.
아래는 동일한 데모입니다 -
예시
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 print_it(self):
curr = self.head
while curr is not None:
print(curr.data)
curr = curr.next
def add_linked_list(my_list_1, my_list_2):
sum_list = LinkedList_structure()
curr_1 = my_list_1.head
curr_2 = my_list_2.head
while (curr_1 and curr_2):
sum_val = curr_1.data + curr_2.data
sum_list.add_vals(sum_val)
curr_1 = curr_1.next
curr_2 = curr_2.next
if curr_1 is None:
while curr_2:
sum_list.add_vals(curr_2.data)
curr_2 = curr_2.next
else:
while curr_1:
sum_list.add_vals(curr_1.data)
curr_1 = curr_1.next
return sum_list
my_list_1 = LinkedList_structure()
my_list_2 = LinkedList_structure()
my_list = input('Enter the elements of the first linked list : ').split()
for elem in my_list:
my_list_1.add_vals(int(elem))
my_list = input('Enter the elements of the second linked list : ').split()
for elem in my_list:
my_list_2.add_vals(int(elem))
sum_list = add_linked_list(my_list_1, my_list_2)
print('The sum of elements in the linked list is ')
sum_list.print_it()입니다. 출력
Enter the elements of the first linked list : 56 34 78 99 54 11 Enter the elements of the second linked list : 23 56 99 0 122 344 The sum of elements in the linked list is 79 90 177 99 176 355
설명
-
'Node' 클래스가 생성됩니다.
-
필수 속성이 있는 또 다른 'LinkedList_structure' 클래스가 생성됩니다.
-
첫 번째 요소, 즉 'head'를 'None'으로 초기화하는 데 사용되는 'init' 기능이 있습니다.
-
스택에 값을 추가하는 데 도움이 되는 'add_vals'라는 메서드가 정의되어 있습니다.
-
연결 목록의 값을 표시하는 데 도움이 되는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
-
두 개의 연결 목록의 해당 요소를 추가하는 데 도움이 되는 'add_linked_list'라는 또 다른 메서드가 정의되어 있습니다.
-
'LinkedList_structure'의 인스턴스 2개가 생성됩니다.
-
두 연결 목록에 요소가 추가됩니다.
-
이러한 연결 목록에서 'add_linked_list' 메서드가 호출됩니다.
-
출력은 콘솔에 표시됩니다.