
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Largest Element in a Doubly Linked List using Python
When it is required to find the largest element in a doubly linked list, a method to add elements to the doubly linked list, a method to print the elements of the doubly linked list, and a method to find the largest element in a doubly linked list are defined.
Below is a demonstration for the same −
Example
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.')
Output
Enter the elements in the doubly linked list 45 12 67 89 234 567 888 44 999 The largest element is 999.
Explanation
The ‘Node’ class is created.
Another ‘DoublyLinkedList_structure’ class with required attributes is created.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.
A method named ‘add_vals’ is defined, that helps add a value to the stack.
Another method named ‘insert_at_end’ is defined, that helps add a value to the end of the doubly linked list.
Another method named ‘find_largest_val’ is defined, that helps find the largest value in the entire doubly linked list.
An instance of the ‘DoublyLinkedList_structure’ is created.
Elements are added to the linked list.
The ‘find_largest_val’ method is called on this doubly linked list.
The output is displayed on the console.