재귀를 사용하지 않고 연결 리스트의 요소를 검색해야 하는 경우, 연결 리스트에 값을 추가하는 방법, 연결 리스트의 요소를 표시하는 방법.
검색 중인 요소의 인덱스를 찾는 데 도움이 되는 메서드도 있습니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self, data):
self.data = data
self.next = None
class my_linked_list:
def __init__(self):
self.head = None
self.last_node = None
def add_value(self, my_data):
if self.last_node is None:
self.head = Node(my_data)
self.last_node = self.head
else:
self.last_node.next = Node(my_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 find_index_val(self, my_key):
curr = self.head
index_val = 0
while curr:
if curr.data == my_key:
return index_val
curr = curr.next
index_val = index_val + 1
return -1
my_instance = my_linked_list()
my_list = [67, 4, 78, 98, 32, 0, 11, 8]
for data in my_list:
my_instance.add_value(data)
print('The linked list is : ')
my_instance.print_it()
print()
my_key = int(input('What value would you search for? '))
index_val = my_instance.find_index_val(my_key)
if index_val == -1:
print(str(my_key) + ' was not found.')
else:
print('Element was found at index ' + str(index_val) + '.')
n = int(input('How many elements would you wish to add ? '))
for i in range(n):
data = int(input('Enter data : '))
my_instance.add_value(data)
print('The linked list is : ')
my_instance.print_it() 출력
The linked list is : 67 4 78 98 32 0 11 8 What value would you search for? 11 Element was found at index 6. How many elements would you wish to add ? 2 Enter data : 111 Enter data : 56 The linked list is : 67 4 78 98 32 0 11 8 111 56
설명
-
'Node' 클래스가 생성됩니다.
-
필수 속성이 있는 또 다른 'my_linked_list' 클래스가 생성됩니다.
-
첫 번째 요소, 즉 'head'를 'None'으로, 마지막 노드를 'None'으로 초기화하는 데 사용되는 'init' 기능이 있습니다.
-
'add_value'라는 또 다른 메서드가 정의되어 있는데, 이 메서드는 연결 목록에 데이터를 추가하는 데 사용됩니다.
-
콘솔에 연결 목록 데이터를 표시하는 데 사용되는 'print_it'이라는 또 다른 메서드가 정의되어 있습니다.
-
사용자가 입력한 요소의 인덱스를 찾는 데 도움이 되는 'find_index_val'이라는 또 다른 메서드가 정의되어 있습니다.
-
my_linked_list' 클래스의 객체가 생성됩니다.
-
목록이 정의됩니다.
-
이 목록은 반복되며 데이터를 추가하기 위해 해당 목록에서 메서드가 호출됩니다.
-
이것은 'print_it' 메소드를 사용하여 콘솔에 표시됩니다.
-
검색할 요소에 대한 사용자 입력을 요청합니다.
-
이에 'find_index_val' 메소드가 호출되고 콘솔에 출력이 표시됩니다.