이중 연결 목록에서 가장 큰 요소를 찾아야 하는 경우 이중 연결 목록에 요소를 추가하는 방법, 이중 연결 목록의 요소를 인쇄하는 방법, 이중 연결 목록에서 가장 큰 요소를 찾는 방법 목록이 정의됩니다.
아래는 동일한 데모입니다 -
예시
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList_structure:
def __init__(self):
self.first = None
self.last = None
def add_vals(self, data):
self.insert_at_end(Node(data))
def insert_at_end(self, newNode):
if self.last is None:
self.last = newNode
self.first = newNode
else:
newNode.prev = self.last
self.last.next = newNode
self.last = newNode
def find_largest_val(my_list):
if my_list.first is None:
return None
largest_val = my_list.first.data
curr = my_list.first.next
while curr:
if curr.data > largest_val:
largest_val = curr.data
curr = curr.next
return largest_val
my_instance = DoublyLinkedList_structure()
my_list = input('Enter the elements in the doubly linked list ').split()
for elem in my_list:
my_instance.add_vals(int(elem))
largest_val = find_largest_val(my_instance)
if largest_val:
print('The largest element is {}.'.format(largest_val))
else:
print('The list is empty.') 출력
Enter the elements in the doubly linked list 45 12 67 89 234 567 888 44 999 The largest element is 999.
설명
-
'Node' 클래스가 생성됩니다.
-
필수 속성을 가진 또 다른 'DoulyLinkedList_structure' 클래스가 생성됩니다.
-
첫 번째 요소, 즉 'head'를 'None'으로 초기화하는 데 사용되는 'init' 기능이 있습니다.
-
스택에 값을 추가하는 데 도움이 되는 'add_vals'라는 메서드가 정의되어 있습니다.
-
이중 연결 목록의 끝에 값을 추가하는 데 도움이 되는 'insert_at_end'라는 또 다른 메서드가 정의되어 있습니다.
-
전체 이중 연결 목록에서 가장 큰 값을 찾는 데 도움이 되는 'find_largest_val'이라는 또 다른 메서드가 정의되어 있습니다.
-
'DoubleLinkedList_structure'의 인스턴스가 생성됩니다.
-
연결 목록에 요소가 추가됩니다.
-
이 이중 연결 목록에서 'find_largest_val' 메서드가 호출됩니다.
-
출력은 콘솔에 표시됩니다.